我在W3School上練習JS,同時嘗試"The Light Bulb"練習我想更改兩個按鈕的功能!
在JavaScript中更改按鈕的功能
什麼,我想要做的是添加另一個按鈕,在點擊將互換標籤「開燈」和「關燈」用的onclick行動一起。
<!DOCTYPE html>
<html>
<body>
<h1>What Can JavaScript Do?</h1>
<p><b><i>JavaScript can change HTML attributes.</i></b></p>
<p>In this case JavaScript changes the src (source) attribute of an image.</p>
<!-- Button1 (LHS) -->
<button id="buttonId1" onclick="document.getElementById('myImage').src='pic_bulboff.gif'">Turn off the light</button>
<!-- Image of the Bulb -->
<img id="myImage" src="pic_bulbon.gif" style="width:100px">
<!-- Button2 (RHS) -->
<button id="buttonId2" onclick="document.getElementById('myImage').src='pic_bulbon.gif'">Turn on the light</button>
<!-- Function to interchange label of both buttons along with the onclick actions -->
<script>
function clickButton() {
<!-- initially button1 is for switching off the button, changing it to turn-on state -->
document.getElementById('buttonId1').innerHTML = 'Turn on the light';
document.getElementById('buttonId1').onclick="document.getElementById('myImage').src='pic_bulbon.gif' " ;
<!-- initially button2 is for switching on the button, changing it to turn-off state -->
document.getElementById('buttonId2').innerHTML = 'Turn off the Light';
document.getElementById('buttonId2').onclick="document.getElementById('myImage').src='pic_bulboff.gif' " ;
}
</script>
<br>
<!-- Adding new button to manipulate button functionality -->
<button onclick="clickButton()" >Do Not Click Me</button>
</body>
</html>
我試圖執行上面的代碼,它會替換上點擊標籤「請勿點擊我」按鈕,但沒有改變的onclick行動!
我需要幫助來實現該功能。
但是,當我們使用按鈕動作,然後onclick被映射與一個字符串和那個時候它的工作,爲什麼它不適用於document.getElementById('buttonId2')。onclick? – user308967