简体   繁体   English

我可以在jQuery的find中使用contains吗?

[英]Can I use contains inside of a find in jQuery?

I have this html: 我有这个HTML:

<table>
    <tr id="1"><td>test</td><td id="90">value</td></tr>
    <tr id="2"><td>another</td><td id="98">somthing</td></tr>
</table>

and this jquery: 这个jquery:

  $("tr td:nth-child(2)").find(":contains('value')").each(function(){
        alert($(this).parent().attr("id"));
            });

I had assumed this would work, but it doesn't alert anything. 我以为这会起作用,但它不会提醒任何事情。 If I remove the find portion it will alert with both values. 如果我删除了find部分,它将提醒两个值。 Is there a way that I can include the find somehow? 有没有办法让我能以某种方式包括这个发现?

Here is the fiddle: 这是小提琴:

http://jsfiddle.net/B4wMp/2/ http://jsfiddle.net/B4wMp/2/

Remove the .find() and move the :contains('value') to the selector 删除.find()并将:contains('value')到选择器

$("tr td:nth-child(2):contains('value')").each(function(){
  alert($(this).parent().attr("id"));
});

Fiddle: http://jsfiddle.net/B4wMp/5/ 小提琴: http//jsfiddle.net/B4wMp/5/

The correct way to do it is like this : 正确的方法是这样的:

$("tr td:nth-child(2):contains('value')").each(function(){
alert($(this).parent().attr("id"));
    });

Why it wasn't working the way you had it written? 为什么它没有像你写的那样工作? Because from the first selector you get the td which has the word "value" in it and the td which has the word "something" in it. 因为从第一个选择器中得到td,其中包含单词“value”,td中包含单词“something”。 After getting that selection, running .find("...") on those elements starts looking for elements inside of what you currently have. 获得该选择后,在这些元素上运行.find(“...”)开始寻找您当前所拥有的元素。 Since both tds don't have any other element inside them, that .find() selector returns nothing. 由于两个tds中都没有任何其他元素,因此.find()选择器不返回任何内容。

You were using find but that's looking for children of the td elements that you've already selected. 你正在使用find但是那里正在寻找你已经选择过的td元素的子元素。 You don't have any children in your td elements. 你的td元素中没有任何子元素。

You want to use filter or merge it into a single selector 您想使用filter或将其合并到单个选择器中

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM