如果元素包含特定的文本字符串,我目前正在尝试简单地发出警报。这是我到目前为止所拥有的-
<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!");
}
我的问题是,无论如何它都会提醒消息,如果我将它更改为不在任何元素中的字符串,它仍会输出提醒。
谁能看出我哪里出错了?
谢谢
最佳答案
您的条件不正确,因为选择器将始终等于 true,因为它返回一个对象,而不是 bool 值。
相反,使用 length
检查选择器是否返回了任何元素:
if ($(".first:contains('first')").length){
alert("Found It!");
}
关于javascript - 使用 JQuery 查找元素中的文本然后执行功能,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9601116/