简体   繁体   中英

Add onclick event to an HMTL element (img) with JavaScript

I have a js function wich create an img tag and append It to a div tag:

function createImg() {
    let image = document.createElement("img");
    image.src = "random.png";
    document.querySelector("div").appendChild(image);

I want to add to this img an onclick event, so that when I click on It another function will runs, How can I do? I alredy searched something on stack and found .addEventListener() & .onclick() but both seem to don't work..

You can add the event listener to the image like:

image.addEventListener('click', function(){
  // do something
})

 var x = 0; function createImg() { let image = document.createElement("img"); image.src = `random${x}.png`; image.addEventListener('click', function() { console.log(this.src) }) x++; document.querySelector("div").appendChild(image); }
 <div></div> <button onclick="createImg()"> button </button>

Add id attribute first

  image.id = "imgDemo";

Then after appending add the event listener like below:

document.getElementById("imgDemo").addEventListener('click', function() {
     //function call here
  }, false);

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