<!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');
檢查'$('#nonexistent')。length'? –
如果你想檢查一個元素是否存在,你需要使用長度 –
http://stackoverflow.com/questions/3086068/how-do-i-check-whether-a-jquery-element-is-in-the-the- dom 檢查這個 – jQuery00