【问题标题】:jQuery contains() - select only the bottom divjQuery contains() - 只选择底部的 div
【发布时间】:2012-09-26 10:48:13
【问题描述】:

好的,所以我正在尝试使用 contains() 选择器来修改 div 的 css。请看小提琴:http://jsfiddle.net/6mdqf/

如您所见,该函数选择了父 div,即使它不直接包含文本“John”;文本保存在子 div 中。 如果您删除父 div,则一切正常。

如何确保只选择包含文本“John”的子 div,而让父 div 和其他子 div 独处?

希望我的问题有意义...

代码:

<div>
    <div>John Resig</div>
    <div>George Martin</div>
    <div>Malcom John Sinclair</div>
    <div>J. Ohn</div>
</div>

还有js

$("div:contains('John')").css("text-decoration", "underline");

【问题讨论】:

标签: jquery contains


【解决方案1】:

由于父 div 具有包含该特定文本的子元素,因此您的选择器会选择父 div 及其子元素,请尝试以下操作。

$("div:not(:has(*)):contains('John')").css("text-decoration", "underline");

http://jsfiddle.net/rwQ3u/

【讨论】:

  • 这个答案太棒了,因为与公认的答案不同,它与上面有多少级别无关。很高兴能解释这是如何工作的。 has(*) 是否只返回有子元素的元素?
  • @JeopardyTempest 谢谢。是的,has(*) 只返回有子元素的元素,:not 排除了选中的元素,所以没有子元素的 div 会被选中。 '*' 不返回 textNodes。有 :empty 选择器,但它只选择没有 childNodes 的元素。
【解决方案2】:

另一种方法是在 div 中调用子元素,并在子元素中使用 contains() 作为选择器。

$("div").children(":contains('John')").css("text-decoration", "underline");​

JSFiddle

【讨论】:

    【解决方案3】:

    因为您首先有一个 div,它在其中搜索并在 div 中找到 John 并全选,试试这个:

    <div>
        <div class="search">John Resig</div>
    
        <div class="search">George Martin</div>
        <div class="search">Malcom John Sinclair</div>
        <div class="search">J. Ohn</div>
    </div>
    ​$(document).ready(function(){
        $("div .search:contains('John')").css("text-decoration", "underline");
    });
    

    【讨论】:

      【解决方案4】:
      $("div>:contains('John')").css("text-decoration", "underline");
      

      编辑的 jsFiddle:http://jsfiddle.net/6mdqf/1/

      【讨论】:

        猜你喜欢
        • 2014-11-25
        • 1970-01-01
        • 2011-01-24
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-09-17
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多