2012-03-07 53 views
1

我想在此刻简单地警告如果一个元素包含特定的文本字符串。以下是我迄今为止 -使用JQuery来查找元素中的文本,然后执行功能

<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!"); 
} 

我的问题是,它会提醒消息不管,I F我将其更改为一个字符串,是不是在任何元素它仍将输出警报。

任何人都可以看到我要去哪里错了吗?

感谢

回答

4

你的条件是不正确的选择将永远等同于真实的,因为它返回一个对象,而不是一个布尔值。

相反,检查是否选择使用length返回的所有元素:

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

Example fiddle

0

如果你想寻找特定的文本,然后使用此:

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