2013-06-19 56 views
0
<!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> 

問:問題與jQuery的CSS選擇

其實,有沒有這樣的ID #nonexistent在我的網頁,但爲什麼這條線仍然運行:console.log('test');

+0

檢查'$('#nonexistent')。length'? –

+0

如果你想檢查一個元素是否存在,你需要使用長度 –

+0

http://stackoverflow.com/questions/3086068/how-do-i-check-whether-a-jquery-element-is-in-the-the- dom 檢查這個 – jQuery00

回答

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

$('#nonexistent')返回一個對象(jQuery對象),以及所有的對象是有一個感實性。您應該改用:

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

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

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

使用.length成員是否存在。

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

要測試某個元素是否存在,請使用長度函數。

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

你不需要> 0但它與可讀性幫助。