jQuery不支持选择顶级nodetext?

每当我需要顶级文本节点时,我必须写下这个长篇故事吗?

$("#hello").clone().children().remove().end().text(); 

为什么没有原生function来支持它?

我不确定为什么没有原生支持。 我想你可以把那些笨重的代码变成一个插件(必须有一个比我选择的更好的名字):

 $.fn.topNodeText = function() { return $(this).clone().children().remove().end().text(); }; $(document).ready(function() { alert($("#blahahah").topNodeText()); }); 
 $.fn.directText = function() { return $.map(this[0].childNodes, function(n){ return n.nodeType === 3 ? n.data : []; }).join(''); }; $(something).directText(); 

什么jQuery没有直接提供,你可以一起破解并插入一个插件:)

这是获取文本节点的一种非常好的方法。

 getTextNodes: function( el ) { var nodes = []; if(el instanceof NodeList || el instanceof HTMLCollection ){ //perhaps a better test for an array/collection of objects is required here? for( var i = 0, j = el.length; i < j; i++ ) { //call this function with each item in the array/collection nodes = nodes.concat( arguments.callee(el[i])); } return nodes; } for( var i = 0, j = el.childNodes.length; i < j; i++ ) { var node = el.childNodes[i]; if( node.nodeType == 3 ) { //ignore whitespace if( /^\s+$/.test( node.nodeValue ) ) continue; nodes.push( Tarjemlo.trim(node.nodeValue) ); } else { //call this function with this child node nodes = nodes.concat( arguments.callee( node ) ); } } return nodes; }