简体   繁体   中英

Javascript : How to make a element clickable that was created in a function

Hey I have a problem that I don't know how to solved. To make simple. I have a script that create element based on what I have get from a server. At moment I create an image with the id "add" And I want when we click on this image to trigger a function so I did a little script

 document.getElementById('add').onclick = function(){ alert('ADD;'); // <- For the test }

But I get a problem when Uncaught TypeError: document.getElementById(...) is null . I thing this because I create this element in the other function and he is not directly in the html code. But I don't know how to solve that.

You have to append the element to the document:

document.appendChild(yourElement); 

Then you have to add an EventListener to your object:

document.getElementById('add').addEventListener("click", 
function() { 
alert('test'); 
});

i think your example is not long enought to answer you properly but to do want you want, you need to create your element, then attach your event to the element. I'm pretty sure you are trying to set the event on a element that doesn't already exist in DOM

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