[英]Replace HTML button by HTML input tag using java script or jQuery
[英]replace a image in html with using of java script
我不明白我在这里做错了什么,我尝试调试代码,但我没有发现我在这里做错了什么。 我尝试使用 java 脚本替换 html 中的图像,我希望能对我的问题提供一些有用的帮助
Html 代码:
<img id = "lamp" src = "js/Capture.PNG"/>
<!--make a button to turn on or off the lamp in this case -->
<button id = "off" name = "offf" onclick="change_attribute()" >Turn off the light</button>
<button id = "on" name = "offf" onclick="change_attribute()"> turn on the light </button>
Java脚本代码:
function change_attribute() {
var x = document.getElementsByName("offf");
if (x.id === "off")
{
document.getElementById('off').src = "js/Capture.PNG/";
}
else
{
document.getElementById('on').src = 'js/Capture2.PNG/'
}
}
getElementsByName(
) 方法返回文档中具有指定名称的所有元素的集合。 您正在尝试引用数组中不存在但实际数组元素上的id
属性。
您可能应该重构您的代码以使用调用change_attribute()
的单个 html 元素,它将分别在打开和关闭之间切换 state。
getElementsByName()
返回指定给定条件的 HTML 元素数组。
在您的情况下,您将获得按钮数组 html 元素,因此,当您访问x.id
时,它会给出错误,因为 x 是数组,而不是 object。
尝试重构您的代码并仅从一个地方调用change_attribute
function change_attribute(e) { if (e.target.id === "off") { document.getElementById('lamp').src = "https://cdn-icons-png.flaticon.com/512/2910/2910914.png"; } else { document.getElementById('lamp').src = 'https://cdn-icons-png.flaticon.com/512/702/702797.png' } }
#lamp{ width: 50px; height: 50px; margin-right:15px; }
<img id="lamp" src ="https://cdn-icons-png.flaticon.com/512/2910/2910914.png"/> <!--make a button to turn on or off the lamp in this case --> <button id="off" class="lightBtn" onclick="change_attribute(event)" >Turn off the light</button> <button id="on" class="lightBtn" onclick="change_attribute(event)"> turn on the light </button>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.