As the other commenters are suggesting the most efficient way to do it seems to be:
(正如其他评论者所建议的那样,最有效的方法似乎是:)
if ($(selector).length ) {
// Do something
}
If you absolutely must have an exists() function - which will be slower- you can do:
(如果你绝对必须有一个exists()函数 - 它会更慢 - 你可以这样做:)
jQuery.fn.exists = function(){return this.length>0;}
Then in your code you can use
(然后在你的代码中你可以使用)
if ($(selector).exists()) {
// Do something
}
As answered here
(在这里回答)
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…