Check if element exists [duplicate]
Possible Duplicates:
Is there an “exists” function for jQuery jQuery determining if element exists on page
if(tr)
is returning true when tr is not an element, how do I check whether it's an element that exists?
var tr = $('#parts-table .no-data').parent();
$('.delete', row).bind('click', function (e) {
that.delete(e.currentTarget);
});
console.log(tr);
if (tr) //ret开发者_JAVA技巧urns true when it shouldn't
Check its length
property:
if(tr.length) {
// exists
}
if(tr)
always evaluates to true because a jQuery object, or any JavaScript Object for that matter, is always truthy.
I always add this little jQuery snippet at the beginning of my JS files
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...
}
That's because tr
is a jQuery object, which is truthy (even when the jQuery object is empty). Use if (tr.length)
instead, which will be true when length
is not zero, false when it is zero. Or alternately, if (tr[0])
.
How about:
if (tr.size() == 0)
try this
var tr = $('#parts-table .no-data').parent().length;
精彩评论