2014-12-22 96 views
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; 
    } 
} 

回答

-1

myFunction第一次運行,即該按鈕的第一次點擊,可變i具有值0等等if語句執行第一替換。

第二次運行時,自上次調用i++;以來,i的值爲1。因此,運行if語句的第二個替代方法(else部分)。

由於maindiv變量僅在已不執行第一替代定義div是未定義在該第二運行。

的解決方案是在else塊也定義div

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

} 
+0

我想你想找到'通過ID,而不是選擇div'。 '#main'下可能有其他'div',queryBySelector返回它找到的第一個。 – jalynn2

+0

@ jalynn2真的,我甚至沒有注意到在'div'上設置了'id'屬性,謝謝! – jrsala