<!doctype html>
<html>
<head>
<meta charset="utf-8" />
<title>Demo</title>
</head>
<body>
</body>
</html>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script>
if ( $( '#nonexistent' ) ) {
console.log('test');
}
</script>
问题:
实际上我的页面中没有此类ID #nonexistent
,但为什么此行仍在运行:console.log('test');
答案 0 :(得分:1)
因为$( '#nonexistent' )
返回一个空集(基本上是一个数组),而空数组在布尔上下文中返回true。
您需要检查$('#nonexistent').length
。
如果您对这是如何运作感兴趣,请阅读this sitepoint article about truthy-/falsyness in javascript。
您也可以使用
// pretty jQuery-like
document.querySelector('#nonexistent')
// or a bit faster faster:
document.getElementById('nonexistent')
答案 1 :(得分:1)
$( '#nonexistent' )
返回一个对象(jQuery对象),所有对象都是肯定的。你应该使用:
if ( $( '#nonexistent' )[0] ) {
console.log('test');
}
或者更好的是,根本不需要jQuery:
if (document.getElementById("nonexistent")) {
console.log("not gonna happen");
}
答案 2 :(得分:0)
使用.length
成员查看是否存在。
if ( $( '#nonexistent' ).length ) {
console.log('test');
}
答案 3 :(得分:0)
要测试元素是否存在,请使用长度函数。
if ( $( '#nonexistent' ).length > 0) {
console.log('test');
}
您不需要> 0
,但它有助于提高可读性。