我在java脚本中有以下代码。当我运行此代码时,我面临一个错误,说div.parentNode为null。如果将2变量main和div作为全局变量,则代码完全正常。为什么会这样?
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;
}
}
答案 0 :(得分:-1)
在第一次运行myFunction
时,即第一次点击按钮,变量i
的值为0
,因此if
语句执行第一个选项。< / p>
在第二次运行中,i
自上次调用执行1
以来值i++;
。因此,运行if
语句的第二个选项(else
部分)。
由于main
和div
变量仅在未执行的第一个备选项中定义,因此在第二次运行时未定义div
。
解决方案是在div
块中定义else
:
function myFunction () {
var div;
if ( i < 1 ) {
var main = document.getElementById("main");
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 {
// get the div we created before
div = document.getElementById('newdiv');
div.parentNode.removeChild(div);
i=0;
}
}