javascript - 如何打开和关闭 bul:但仅使用 1 个按钮?
问题描述
这是来自 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">
推荐阅读
- mysql - ERROR 1045 (28000): Access denied for user 'root'@'localhost' 在启动 MYSQL 时
- python - Ray:如何在一个 GPU 上运行多个演员?
- android - 从 Android AppWidget 播放/控制歌曲
- c++ - 为什么不管大小写程序都不是输出真值?
- sql - 在日期范围之间按日期名称查找员工班次
- android - 在导航工具栏下方切换 Google Admob 横幅
- html - CSS 位置未按预期工作。如何解决?
- javascript - 如何根据 'DD-MM-YYYY HH:mm:ss' 格式的日期时间以降序对数组进行排序?
- php - 如何获取所有记录并按 create_at 分组(仅限日期)
- error-handling - Rust Arc/Mutex 尝试宏借用内容