私はW3SchoolでJSを練習していますが、"The Light Bulb"を試してみました。私は2つのボタンの機能を変更したかったのです!私がやりたいこと
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')では機能しませんか。 – user308967