正如你所知
$("#ID")
返回具有 ID 的元素。
但是即使没有元素,此代码也始终返回。
alert($("#htrBuyerCouponNotice"));
alert(document.getElementById("htrBuyerConponNotice"));
在这种情况下。
这两行结果是不同的。
我想检查是否有一个元素具有 htrBuyerCouponNotice
。
document.getElementByID
如果没有元素,则返回 null。
最佳答案
您可以查看length
jQuery 对象的属性来确定匹配元素的数量,例如:
alert($(selector).length);
您可以直接在 if
语句上使用它,例如:
var $el = $(selector);
if ($el.length) { // only 0 will coerce to false
// ...
}
但大多数时候你并不需要知道选择器是否匹配元素,因为 jQuery 内置方法将被简单地忽略,例如:
$('#nonExistent').hide();
即使没有找到该元素,上述语句也不会导致任何错误。
jQuery 还有 size
方法,但我建议您直接使用 length
属性,因为它是公开访问的,即 size
方法稍微慢一些,因为它只是一个返回 length
属性值的函数。
关于javascript - jquery中按id选择,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2414983/