简体   繁体   English

使用JQuery在元素中查找文本然后执行函数

[英]Using JQuery to find text in an element then perform function

I am trying to at the moment simply alert if an element contains specific text string. 我现在试图只是警告一个元素是否包含特定的文本字符串。 Here is what I have so far - 这是我到目前为止 -

<div class="first">This is the first div</div>
<div class="second">This is the second div</div>


if($(".first:contains('first')")){
    alert("Found It!");
}

My problem is, it will alert the message regardless, I f I change it to a String that is not in any of the elements it will still output the alert. 我的问题是,它会警告消息,无论如何,我将它更改为一个不在任何元素中的字符串,它仍将输出警报。

Can anyone see where I am going wrong? 任何人都可以看到我错在哪里?

Thanks 谢谢

Your condition is incorrect as the selector will always equate to true because it returns an object, not a boolean value. 您的条件不正确,因为选择器将始终等于true,因为它返回一个对象,而不是布尔值。

Instead, check to see if the selector returned any elements by using length : 相反,检查选择器是否使用length返回任何元素:

if ($(".first:contains('first')").length){
    alert("Found It!");
}

Example fiddle 示例小提琴

If you want to look for specific texts then use this: 如果您想查找特定文本,请使用以下内容:

if($(".first").text().indexOf("first")>0){
    alert("Found It!");
}

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

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