javascript - 使用 JQuery 查找元素中的文本然后执行功能

标签 javascript jquery html

如果元素包含特定的文本字符串,我目前正在尝试简单地发出警报。这是我到目前为止所拥有的-

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

Example fiddle

关于javascript - 使用 JQuery 查找元素中的文本然后执行功能,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9601116/

相关文章:

javascript - Express.js : Execution doesn't stop after error handler. 为什么?

javascript - 使用 if 语句定义函数

javascript - jQuery-File-Upload 未在 Internet Explorer (IE9) 中触发完成回调

javascript - 如果在 jQuery 中找不到 ID,则显示不同的结果

javascript - 在不使用 unbind/removeAttr 的另一个函数中更新 onclick 函数

javascript - 在ajax成功时重新绘制Jqplot

html - C 客户端/服务器与 HTML 页面的通信

javascript - 从外部 Controller 调用 Angular JS

javascript - 每次打开模态窗口时重新加载模态体

jquery - 选中复选框时如何使类可见