I want to make a simple switch of <img src="...">
depending on the present src
with JavaScript. So if the image #plus_1
is clicked, the script should check if the string 'plus'
is in the src attribute, and if yes, the src attribute should change. Not sure what mistake I made, help would be very much appreciated!
JavaScript:
function ek_ak(id) {
var ement = document.getElementById(id);
if (ement.img.src.includes("plus") == true) {
ement.img.src == "minusred.png";}
}
HTML
<img src="plusred.png" id="plus_1" onclick="ek_ak('plus_1')"/>
A few pointers:
ement
is already a DOM element: it has no img
property but you can access src
on it directly; String#includes
; =
as the assignment operator, instead of ==
(loose comparison). function ek_ak (id) { var ement = document.getElementById(id); if (/plus/.test(ement.src)) { ement.src = "minusred.png" console.log(ement.src) } }
<img src="plusred.png" id="plus_1" onclick="ek_ak('plus_1')" />
onclick="ek_ak(this)
. This will avoid the unnecessary call to retrieve the element. src
you can simply call element.src
. The element is your img
.includes(..)
is returning a boolean value. You do not need to add == true
. element.src == "minusred.png
. ==
is used to compare elements not to assign. You should use =
function ek_ak(element) { console.log("Current src = " + element.src); if (element.src.includes("plus")) { element.src = "minusred.png"; console.log("Next src = " + element.src); } }
<img src="plusred.png" id="plus_1" onclick="ek_ak(this)" />
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.