一个直接包含文本的元素的jQuery选择器? [英] jQuery selector for an element that directly contains text?

查看:189
本文介绍了一个直接包含文本的元素的jQuery选择器?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我能够使用:contains 选择器使其部分工作,但我的问题是,如果元素包含一个包含仍然返回的文本的元素。例如:

I was able to get this partially working using the :contains selector, but my problem is if an element contains an element that contains the text it is still returned. For example:

$('div:contains("test")')

将选择以下两个div:

Will select both divs below:

<div>something else
   <div>test</div>
</div>

小提琴: http://jsfiddle.net/TT7dR/

如何只选择直接包含文本的div?这意味着在上面的例子中只会选择子div。

How can I select only divs that "directly" contain the text? Meaning that in the above example only the child div would be selected.

更新:

只是为了澄清,如果我在搜索文本别的而不是test,那么我只想找到父div。

Just to clarify, if I were searching for the text "something else" instead of "test" then I would like to only find the parent div.

推荐答案

$('div>:contains(test)')不是一般解决方案,它只适用于您的具体示例。它仍然匹配其后代包含文本 test 的任何元素,只要其父元素是 div

$('div>:contains("test")') is not a general solution, it only works for your specific example. It still matches any element whose descendants contain the text test, as long as its parent is a div.

实际上目前没有选择器只会选择包含目标文本的文本节点的直接父项。要做到这一点,你必须自己走DOM树,检查你找到的目标文本的每个文本节点,或者写一个插件来做同样的事情。它会很慢,但不会像那样缓慢:包含已经是(它不是标准的CSS选择器,所以你不会得到浏览器本地的快速选择器支持)。

There is in fact currently no selector that will select only direct parents of text nodes containing your target text. To do it you would have to walk the DOM tree yourself checking each text node you find for the target text, or write a plugin to do the same. It'd be slow, but then not as slow as :contains already is (it's not a standard CSS selector so you don't get browser-native fast selector support).

这是一个可以用作起点的普通DOM函数。可以改进在相邻(非规范化)文本节点中查找文本,或者将其隐藏在插件/选择器扩展中。

Here's a plain DOM function you could use as a starting point. It might be improved to find text in adjacent (non-normalised) text nodes, or to hide it in a plugin/selector-extension.

function findElementsDirectlyContainingText(ancestor, text) {
    var elements= [];
    walk(ancestor);
    return elements;

    function walk(element) {
        var n= element.childNodes.length;
        for (var i= 0; i<n; i++) {
            var child= element.childNodes[i];
            if (child.nodeType===3 && child.data.indexOf(text)!==-1) {
                elements.push(element);
                break;
            }
        }
        for (var i= 0; i<n; i++) {
            var child= element.childNodes[i];
            if (child.nodeType===1)
                walk(child);
        }
    }
}

这篇关于一个直接包含文本的元素的jQuery选择器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆