简体   繁体   中英

replace a image in html with using of java script

I don't understand what am I doing wrong here, I try to debug the code, but I did not found what I did wrong here. I tried to replace the image in html with using of java script, I would appreciate some useful help for my problem

Html code:

<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> 
    

Javacript code:

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/'
    }
    
}

The getElementsByName( ) method returns a collection of all elements in the document with the specified name. you are trying to reference an id property which doesn't exist in the array but on the actual array elements.

You should propbably refactor your code to use a single html element which calls the change_attribute() and it will toggle the state respectively between on and off.

getElementsByName() returns an array of HTML elements that specifies the given condition.

In your condition you are getting array of buttons html element as a result of which, when you are accessing x.id then it is giving error as x is array, rather than object.

try to refactor your code and call change_attribute from one place only

 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>

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