0
我在java腳本中有以下代碼。當我運行這段代碼時,我遇到了一個錯誤,說div.parentNode爲空。如果將2個變量main和div作爲全局變量,那麼代碼工作得很好。爲什麼這樣?JavaScript是否具有塊級別範圍?
var i = 0;
var button = document.getElementById("myButton");
button.addEventListener('click',myFunction,false);
function myFunction() {
if (i < 1) {
var main = document.getElementById("main");
var div = document.createElement("div");
main.appendChild(div);
var para = document.createElement("p");
div.appendChild(para);
div.setAttribute("id","newdiv");
para.innerHTML = "This is a new div that has been created using java script.This is a new div that has been created using java script.This is a new div that has been created using java script.This is a new div that has been created using java script.This is a new div that has been created using java script.";
i++
}
else {
div.parentNode.removeChild(div);
i=0;
}
}
我想你想找到'通過ID,而不是選擇div'。 '#main'下可能有其他'div',queryBySelector返回它找到的第一個。 – jalynn2
@ jalynn2真的,我甚至沒有注意到在'div'上設置了'id'屬性,謝謝! – jrsala