代码之家  ›  专栏  ›  技术社区  ›  Waheed

jquery不支持选择顶级nodetext?

  •  2
  • Waheed  · 技术社区  · 16 年前

    每当我需要顶层的文本节点时,我必须编写这个长篇故事?

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

    为什么没有本地函数来支持它?

    3 回复  |  直到 10 年前
        1
  •  1
  •   karim79    16 年前

    我不知道为什么没有本地支持。我想你可以把那一行笨拙的代码变成一个插件(一定有比我选择的更好的名字):

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

    jquery没有直接提供的东西,你可以一起破解并放入一个插件:)

        3
  •  0
  •   Waheed    10 年前

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

    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;
        }