简体   繁体   English

jquery中的css选择器问题

[英]issue with css selector in jquery

<!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>

Question: 题:

Actually there is no such id #nonexistent in my page, but why this line still runs: console.log('test'); 实际上我的页面中没有这样的id #nonexistent ,但为什么这行还在运行: console.log('test');

Because $( '#nonexistent' ) returns an empty set (which is an basically an array) and empty arrays yield true in boolean context. 因为$( '#nonexistent' )返回一个空集(基本上是一个数组),而空数组在布尔上下文中返回true。

You need to check $('#nonexistent').length instead. 你需要检查$('#nonexistent').length

If you are interested about how this exactly works, read into this sitepoint article about truthy-/falsyness in javascript . 如果您对这是如何工作感兴趣,请阅读这篇关于javascript中的truthy- / falsyness的sitepoint文章

You could as well use 你也可以使用

// pretty jQuery-like
document.querySelector('#nonexistent')
// or a bit faster faster:
document.getElementById('nonexistent')

$( '#nonexistent' ) returns an object (jQuery object), and all objects have a truthiness of yes. $( '#nonexistent' )返回一个对象(jQuery对象),所有对象都是肯定的。 You should instead use: 您应该使用:

if ( $( '#nonexistent' )[0] ) { 
  console.log('test');
}

Or better yet, no need for jQuery at all: 或者更好的是,根本不需要jQuery:

if (document.getElementById("nonexistent")) {
  console.log("not gonna happen");
}

Use the .length member to see if it exists. 使用.length成员查看它是否存在。

if ( $( '#nonexistent' ).length ) { 
    console.log('test');
}

To test whether an element exists use the length function. 要测试元素是否存在,请使用length函数。

if ( $( '#nonexistent' ).length > 0) { console.log('test'); }

You don't need the > 0 but it helps with readability. 您不需要> 0但它有助于提高可读性。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM