[英]Clicked on an element which has href attribute, then change another elements style in javascript, how to do that?
[英]How do I change an element attribute everytime it is clicked in javascript?
我有兩張圖片,我嘗試使用 if 和 else 語句更改每次單擊 img 元素時顯示的圖片。 但是圖像只會在第一次發生變化,第二次點擊不會變回圖像。
<div class="mode-change">
<img id="modeImg" class="" src="media/light.png" alt="Mode">
</div>
請注意,我不知道 jQuery。
我嘗試在每次單擊元素時使用 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)
}
}
在嘗試了@Emmanuel Villalobos 提供的答案並添加了正確的運算符之后,但我注意到即使 src 是“media/light.png”,控制台也只返回 else 語句的值。 所以我試着像這樣在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)
}
}
控制台返回了http://localhost/study/media/light.png
中的絕對鏈接,而不是我在 HTML 代碼中輸入的media/light.png
。
您的條件中的問題是您使用了一個等號而不是兩個或三個進行比較。
這個 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.