[英]How do I change an element attribute everytime it is clicked in javascript?
I have two images, and I'm trying to change the image displayed every time the img element is clicked using the if and else statements.我有两张图片,我尝试使用 if 和 else 语句更改每次单击 img 元素时显示的图片。 But the image only changes the first time, and clicking it the second time won't change the image back.
但是图像只会在第一次发生变化,第二次点击不会变回图像。
<div class="mode-change">
<img id="modeImg" class="" src="media/light.png" alt="Mode">
</div>
Please note that I don't know jQuery.请注意,我不知道 jQuery。
I tried using the if and else statement to change the picture every time the element is clicked, but the code won't run past the if statement.我尝试在每次单击元素时使用 if 和 else 语句来更改图片,但代码不会运行通过 if 语句。
let modeImg = document.getElementById("modeImg");
modeImg.addEventListener("click", changePic);
function changePic() {
if (modeImg.src === "media/light.png") {
modeImg.src = "media/dark.png";
console.log(modeImg.src);
} else {
modeImg.src = "media/light.png";
console.log(modeImg.src)
}
}
After trying out the answer provided by @Emmanuel Villalobos, and added the right operator, but I noticed that the console only returned the value of the else statement, even when the src is "media/light.png".在尝试了@Emmanuel Villalobos 提供的答案并添加了正确的运算符之后,但我注意到即使 src 是“media/light.png”,控制台也只返回 else 语句的值。 So I tried to return the output of the image src before the if statement like so,
所以我试着像这样在if语句之前返回图像src的output,
function changePic() {
console.log(modeImg.src);
if (modeImg.src === "media/light.png") {
modeImg.src = "media/dark.png";
console.log(modeImg.src);
} else {
modeImg.src = "media/light.png";
console.log(modeImg.src)
}
}
The console returned the absolute link as in http://localhost/study/media/light.png
instead of the media/light.png
I put in my HTML code.控制台返回了
http://localhost/study/media/light.png
中的绝对链接,而不是我在 HTML 代码中输入的media/light.png
。
The problem in your conditional is that you used a single equal sign instead of two or three to compare.您的条件中的问题是您使用了一个等号而不是两个或三个进行比较。
This function should work as you expect:这个 function 应该可以如你所愿工作:
function changePic() { if (modeImg.src.contains("media/light.png")) { modeImg.src = "media/dark.png"; console.log(modeImg.src); } else { modeImg.src = "media/light.png"; console.log(modeImg.src) } }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.