-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!
沒有區別。我無法複製:https://jsfiddle.net/mfuyxgoL/1/。請添加一個問題的工作示例。 –
不aaa.length!= 0是否意味着該元素存在? –
是的,但我只是這樣做,從兩種方法得到相同的結果。我剛剛更新了小提琴以顯示所有可能的結果:https://jsfiddle.net/mfuyxgoL/2/。無論哪種方式,你的代碼應該工作。 –