简体   繁体   中英

Src attribute switch with JavaScript

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;
  • Regular expressions can be used instead of String#includes ;
  • You should use = 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')" /> 

  • You can directly send the element to the function using onclick="ek_ak(this) . This will avoid the unnecessary call to retrieve the element.
  • To get the src you can simply call element.src . The element is your img
  • The call .includes(..) is returning a boolean value. You do not need to add == true .
  • You were using 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM