【问题标题】:issue with css selector in jqueryjquery中的css选择器问题
【发布时间】:2013-06-19 07:49:21
【问题描述】:
<!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>

问题:

其实我的页面里没有#nonexistent这样的id,但是为什么这条线还在运行:console.log('test');

【问题讨论】:

标签: jquery


【解决方案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')

【讨论】:

    【解决方案2】:

    $( '#nonexistent' ) 返回一个对象(jQuery 对象),所有对象的真实性都是 yes。你应该改用:

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

    或者更好的是,根本不需要 jQuery:

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

    【讨论】:

      【解决方案3】:

      使用.length 成员查看它是否存在。

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

      【讨论】:

        【解决方案4】:

        要测试元素是否存在,请使用长度函数。

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

        您不需要&gt; 0,但它有助于提高可读性。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2011-08-13
          • 2012-03-20
          • 2012-01-20
          • 1970-01-01
          相关资源
          最近更新 更多