如何打开和关闭灯泡:但仅使用 1 个按钮?

问题描述 投票:0回答:2

这是来自 w3schools 的代码。 我想打开和关闭灯泡,但使用相同的按钮。 尽可能简单。 感谢您的每一个回答:)

<html>
<body>

<h2>What Can JavaScript Do?</h2>

<p>JavaScript can change HTML attribute values.</p>


<button onclick="document.getElementById('myImage').src='pic_bulbon.gif'">Turn on the light</button>

<img id="myImage" src="pic_bulboff.gif" style="width:100px">

<button onclick="document.getElementById('myImage').src='pic_bulboff.gif'">Turn off the light</button>

</body>
</html>
javascript
2个回答
1
投票

这是一种方法。

// Add an on-click handler to the button
document.getElementById("action-btn").onclick = (e) => {
    // Get the image
    let image = document.getElementById("myImage");
    // Check for the word "off"
    if (image.src.includes("off")) {
        // Set image to alternate
        image.src = "pic_bulbon.gif";
        // Set text of button
        e.srcElement.textContent = "Turn off the light";
    }
    else {
        image.src = "pic_bulboff.gif";
        e.srcElement.textContent = "Turn on the light";
    }
}
<h2>What Can JavaScript Do?</h2>
<p>JavaScript can change HTML attribute values.</p>
<button id="action-btn">Turn on the light</button>
<img id="myImage" src="pic_bulboff.gif" style="width:100px">


0
投票

// Add an on-click handler to the button
document.getElementById("action-btn").onclick = (e) => {
    // Get the image
    let image = document.getElementById("myImage");
    // Check for the word "off"
    if (image.src.includes("off")) {
        // Set image to alternate
        image.src = "pic_bulbon.gif";
        // Set text of button
        e.srcElement.textContent = "Turn off the light";
    }
    else {
        image.src = "pic_bulboff.gif";
        e.srcElement.textContent = "Turn on the light";
    }
}
<h2>What Can JavaScript Do?</h2>
<p>JavaScript can change HTML attribute values.</p>
<button id="action-btn">Turn on the light</button>
<img id="myImage" src="pic_bulboff.gif" style="width:100px">

© www.soinside.com 2019 - 2024. All rights reserved.