Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
324 views
in Technique[技术] by (71.8m points)

javascript - 如何使用jQuery选择文本节点?(How do I select text nodes with jQuery?)

I would like to get all descendant text nodes of an element, as a jQuery collection.(我想获取一个元素的所有后代文本节点,作为jQuery集合。)

What is the best way to do that?(最好的方法是什么?)   ask by Christian Oudard translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

jQuery doesn't have a convenient function for this.(jQuery对此没有方便的功能。)

You need to combine contents() , which will give just child nodes but includes text nodes, with find() , which gives all descendant elements but no text nodes.(您需要将contents()仅提供子节点但包括文本节点)与find() ,后者将提供所有后代元素,但不提供文本节点。) Here's what I've come up with:(这是我想出的:)
var getTextNodesIn = function(el) {
    return $(el).find(":not(iframe)").addBack().contents().filter(function() {
        return this.nodeType == 3;
    });
};

getTextNodesIn(el);

Note: If you're using jQuery 1.7 or earlier, the code above will not work.(注意:如果您使用的是jQuery 1.7或更早版本,则上面的代码将不起作用。)

To fix this, replace addBack() with andSelf() .(要解决此问题,请用addBack()替换andSelf()) andSelf() is deprecated in favour of addBack() from 1.8 onwards.(andSelf()从1.8开始不推荐使用addBack())

This is somewhat inefficient compared to pure DOM methods and has to include an ugly workaround for jQuery's overloading of its contents() function (thanks to @rabidsnail in the comments for pointing that out), so here is non-jQuery solution using a simple recursive function.(与纯DOM方法相比,此方法效率低下,并且必须为jQuery的 content contents()函数的重载提供一个丑陋的解决方法 (感谢注释中的@rabidsnail指出),因此这是使用简单递归的非jQuery解决方案功能。)

The includeWhitespaceNodes parameter controls whether or not whitespace text nodes are included in the output (in jQuery they are automatically filtered out).(includeWhitespaceNodes参数控制输出中是否包含空格文本节点(在jQuery中,它们会自动过滤掉)。)

Update: Fixed bug when includeWhitespaceNodes is falsy.(更新:修复了includeWhitespaceNodes错误时的错误。)

function getTextNodesIn(node, includeWhitespaceNodes) {
    var textNodes = [], nonWhitespaceMatcher = /S/;

    function getTextNodes(node) {
        if (node.nodeType == 3) {
            if (includeWhitespaceNodes || nonWhitespaceMatcher.test(node.nodeValue)) {
                textNodes.push(node);
            }
        } else {
            for (var i = 0, len = node.childNodes.length; i < len; ++i) {
                getTextNodes(node.childNodes[i]);
            }
        }
    }

    getTextNodes(node);
    return textNodes;
}

getTextNodesIn(el);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...