javascript有块级别范围?

时间:2014-12-22 17:21:04

标签: javascript html

我在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;
    }
}

1 个答案:

答案 0 :(得分:-1)

在第一次运行myFunction时,即第一次点击按钮,变量i的值为0,因此if语句执行第一个选项。< / p>

在第二次运行中,i自上次调用执行1以来值i++;。因此,运行if语句的第二个选项(else部分)。

由于maindiv变量仅在未执行的第一个备选项中定义,因此在第二次运行时未定义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;
    }

}