在開發過程中,動輒需要判斷「這個元素到底存不存在」。這裡整理幾種常見寫法,涵蓋原生 JS 與 jQuery。
if("periodPerMonth" in document.theForm)
{
return true;
}
else{
return false;
}
if(document.getElementById("XXX"))
{
//存在
}
if(document.theForm.periodPerMonth)
{
//存在
}
或:
if(typeof(document.theForm.periodPerMonth)=="object")
{
//存在
}
if(document.theForm)
{
//存在
}
if ( $("#someID").length > 0 ) {
$("#someID").text("hi");
}
實務上,用 jQuery 的 .length 判斷最為簡潔直觀;而原生寫法中,getElementById 找不到時會回傳 null,因此可以直接放進 if 條件裡做真偽判斷。