jQuery有没有“存在”功能?

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

我现在的代码是这样的:

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

有没有更好的方法来解决这个问题? 也许是一个插件或功能?


在JavaScript中,一切都是'真的'或'虚假的',而对于数字0 (和NaN)则意味着false ,其他所有事情都是true 。 所以你可以写:

if ($(selector).length)

你不需要>0部分。


是!

jQuery.fn.exists = function(){ return this.length > 0; }

if ($(selector).exists()) {
    // Do something
}

这是为了回应:与Jeff Atwood合作的“牧群规范”播客


如果你使用过

jQuery.fn.exists = function(){return ($(this).length > 0);}
if ($(selector).exists()) { }

你会暗示链接是不可能的。

这会更好:

jQuery.exists = function(selector) {return ($(selector).length > 0);}
if ($.exists(selector)) { }

另外,从常见问题解答:

if ( $('#myDiv').length ) { /* Do something */ }

您也可以使用以下内容。 如果jQuery对象数组中没有值,则获取数组中的第一个项目将返回undefined。

if ( $('#myDiv')[0] ) { /* Do something */ }
链接地址: http://www.djcxy.com/p/269.html

上一篇: Is there an "exists" function for jQuery?

下一篇: How to check if an element is off