javascript - jQuery 是否有 "exists"函数?

标签 javascript jquery

如何检查 jQuery 中的元素是否存在?

我当前的代码是这样的:

if ($(selector).length > 0) {
    // Do something
}

有没有更优雅的方法来解决这个问题?也许是插件或函数?

最佳答案

在 JavaScript 中,一切都是“真”或“假”,对于数字来说,0 表示 false,其他一切都 true。所以你可以写:

if ($(selector).length)

您不需要 >0 部分。

关于javascript - jQuery 是否有 "exists"函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43581248/

相关文章:

javascript - jQuery 拖动/调整大小与 CSS 变换比例

javascript - Base64字符串在客户端压缩,在服务器端解压

javascript - 根据 html 表中所做的选择更改 google 标记的颜色

php - 鼠标移出时隐藏子菜单

php - jQuery AJAX 多次提交到 PHP 脚本

javascript - 缩放时保持建议框 div 相对于输入

jquery - DIV/表头在底部,jSON 数据在顶部?

javascript - Magento Bundle 产品中缺少价格字段

Zapier 中的 Javascript 返回多个值以发布到 Airtable 数据库

javascript - 求代码显示两个公共(public)IP网络摄像头