Javascript 检查元素是否存在

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4795928/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 14:07:58  来源:igfitidea点击:

Check if element exists

javascriptjquery

提问by Webnet

Possible Duplicates:
Is there an “exists” function for jQuery
jQuery determining if element exists on page

可能的重复项:
是否有 jQuery jQuery的“存在”函数来
确定页面上是否存在元素

if(tr)is returning true when tr is not an element, how do I check whether it's an element that exists?

if(tr)当 tr 不是元素时返回 true,我如何检查它是否是一个存在的元素?

var tr = $('#parts-table .no-data').parent();
$('.delete', row).bind('click', function (e) {
  that.delete(e.currentTarget);
});
console.log(tr);
if (tr) //returns true when it shouldn't

回答by karim79

Check its lengthproperty:

检查其length属性:

if(tr.length) {
    // exists
}

if(tr)always evaluates to true because a jQuery object, or anyJavaScript Object for that matter, is always truthy.

if(tr)总是评估为真,因为 jQuery 对象或任何JavaScript 对象总是为真。

回答by Dutchie432

I always add this little jQuery snippet at the beginning of my JS files

我总是在我的 JS 文件的开头添加这个小的 jQuery 片段

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

This uses the same approach many here have suggested, but it also allows you to access whether or not an object exists like this:

这使用了这里许多人建议的相同方法,但它也允许您访问对象是否存在,如下所示:

if ( $('#toolbar').exists() ){
    $('#toolbar').load(..., function(){...});
    //etc...
}

回答by T.J. Crowder

That's because tris a jQuery object, which is truthy (even when the jQuery object is empty). Use if (tr.length)instead, which will be true when lengthis not zero, false when it is zero. Or alternately, if (tr[0]).

那是因为tr是一个 jQuery 对象,它是真实的(即使 jQuery 对象为空)。if (tr.length)改为使用,当length不为零时为真,为零时为假。或者,if (tr[0]).

回答by Mark Robinson

How about:

怎么样:

if (tr.size() == 0) 

回答by Harish

try this

尝试这个

var tr = $('#parts-table .no-data').parent().length;