简体   繁体   中英

Why src in this.id.src undefined (in debugger) [inside an iife]

Why is the src in this.id.src undefined in debugger? I don't understand why this doesn't work. I've had this working before, but with a specific id (not this.id) Does anyone have any suggestions?

 document.getElementById("a1").addEventListener("click", myFunction); function myFunction (id) { console.log(this.id); // works this.id.src="images/red.jpg"; }
 <div> <img id="a1" src="images/black.jpg"> </div>

There is no src property on the id property. You must used it directly this.src . And the parameter that is passed to the function is the event not the id:

 document.getElementById("a1").addEventListener("click", myFunction); function myFunction(e) { this.src = "http://via.placeholder.com/150x150"; }
 <div> <img id="a1" src="http://via.placeholder.com/100x100"> </div>

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