这是来自 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>
这是一种方法。
// 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">
// 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">