2016-03-07 28 views
-2

document.getElementById(id)$("#"+id).length有什麼區別?

我有一個div寬度與ID document.getElementById(id)返回true,而$("#" + id).length返回0。爲什麼是這樣?

$(document).ready(function() { 
    if (document.getElementById(go_to_comment)){ 
     alert("the element exists"); 
    } 

    var aaa = $('#' + go_to_comment); 
    if (aaa.length == 0) { 
     alert("the element does not exist"); 
    } 
}); 

爲什麼兩個alert語句都被執行?如果document.getElementById(go_to_comment)爲真,那麼aaa.length不應該爲0!

+1

沒有區別。我無法複製:https://jsfiddle.net/mfuyxgoL/1/。請添加一個問題的工作示例。 –

+0

不aaa.length!= 0是否意味着該元素存在? –

+0

是的,但我只是這樣做,從兩種方法得到相同的結果。我剛剛更新了小提琴以顯示所有可能的結果:https://jsfiddle.net/mfuyxgoL/2/。無論哪種方式,你的代碼應該工作。 –

回答

0

請在下方找到jsfiddle鏈接以獲取答案。 jsfiddle

$(document).ready(function() { 
var go_to_comment="comment"; 
console.log(document.getElementById(go_to_comment)) 
if (document.getElementById(go_to_comment)){ 
    alert("the element exists"); 
} 

var aaa = $('#' + go_to_comment + ""); 
if (aaa.length == 0) { 
    alert("the element does not exist"); 
} 
}); 
相關問題