這是最常見的誤解。下面這種寫法永遠為真:
if($("#id")){ }else{ }
原因很簡單:$("#id") 無論元素存不存在,都會回傳一個 jQuery 物件,而物件在條件判斷中恆為真。
正確做法是檢查長度屬性:
if($("#id").length > 0){ }else{ }
也可以取出原生 DOM 節點來判斷:
if($("#id")[0]){ } else { }
或者乾脆用原生寫法,最直接:
if(document.getElementById("id")){ } else { }
<p>one</p>
<div id="ch">
<span>two</span>
</div>
function jq(){
alert($("#ch").children().html());
}
$("#ch").children() 取得子元素集合 [ <span>two</span> ],因此 .html() 的結果是 two。
<div id="ch">
<span>two</span>
<span id="sp">three</span>
</div>
$(function(){
alert($("#ch").children("#sp").html());
});
第一次呼叫得到 [<span>two</span><span id="sp">three</span>],加上 "#sp" 過濾後剩下 [<span id="sp">three</span>]。
children() 只看直接子元素,find() 則會深入所有後代。若只想取下一層,用 children 更精準也更省資源;這在巢狀結構(例如表格裡再嵌表格)時尤其重要,否則很容易誤傷到內層的元素。