2017-02-09 102 views
0

我的代碼似乎有一個問題,我不知道如何解決。我對這個東西非常陌生,幾乎不知道我在做什麼。每次運行我的代碼時都會彈出此錯誤消息。我試圖讓你點擊藍色框消失的按鈕。當你再次點擊該按鈕時,藍色框再次出現,綠色框消失。這裏是我的代碼:未捕獲TypeError:無法讀取屬性'樣式'null

<script type="text/javascript"> 
    function toggle_visibility(id1,id2){ 
    var e1 = document.getElementById(id1); 
    var e2 = document.getElementById(id2); 

    if (e1.style.visibility == 'hidden') { 
     e1.style.visibility = 'visible'; 
     e2.style.visibility = 'visible';} 
     else{ 
     e1.style.visibility = 'hidden'; 
     e2.style.visibility = 'hidden'; 
     } 
     } 
</script> 
<div class="square" id="bluebox" style="visibility:visible"></div><br> 
<div class="box" id="greenbox" style="visibility:visbible"></div><br> 
<button onclick=" toggle_visibility(greenbox,bluebox)">Pls Work</button> 

回答

0

你需要引號添加到函數的參數:

<button onclick="toggle_visibility('greenbox','bluebox')">Pls Work</button> 

他們不是變量,它們都是字符串。

0

您必須將id的兩個元素都傳遞給函數字符串

function toggle_visibility(id1, id2) { 
 
    var e1 = document.getElementById(id1); 
 
    var e2 = document.getElementById(id2); 
 

 
    if (e1.style.visibility == 'hidden') { 
 
     e1.style.visibility = 'visible'; 
 
     e2.style.visibility = 'visible'; 
 
    } else { 
 
     e1.style.visibility = 'hidden'; 
 
     e2.style.visibility = 'hidden'; 
 
    } 
 
    }
.square, .box { 
 
    height: 50px; 
 
    width: 50px; 
 
    visibility: hidden; 
 
} 
 

 
#greenbox { 
 
    background-color: green; 
 
} 
 

 
#bluebox { 
 
    background-color: blue; 
 
}
<div class="square" id="bluebox"></div> 
 
<br> 
 
<div class="box" id="greenbox"></div> 
 
<br> 
 
<button onclick="toggle_visibility('bluebox', 'greenbox')">Pls Work</button>

0

參數id不是從HTML正確傳遞,你需要正確地傳遞ID喜歡onclick="toggle_visibility('greenbox','bluebox')"

下面的代碼應該爲你工作。

function toggle_visibility(id1,id2){ 
 
    var e1 = document.getElementById(id1); 
 
    var e2 = document.getElementById(id2); 
 

 
    if (e1.style.visibility == 'hidden') { 
 
     e1.style.visibility = 'visible'; 
 
     e2.style.visibility = 'visible';} 
 
     else{ 
 
     e1.style.visibility = 'hidden'; 
 
     e2.style.visibility = 'hidden'; 
 
     } 
 
     }
<div class="square" id="bluebox" style="visibility:visible"></div><br> 
 
<div class="box" id="greenbox" style="visibility:visbible"></div><br> 
 
<button onclick="toggle_visibility('greenbox','bluebox')">Pls Work</button>

+0

謝謝!很棒! –

相關問題