Beginner programmer here-I am making an app that generates list items with a dynamically created button as a child of the 'li' element. I want to assign an onClick function to this dynamically created button but nothing seems to work. I have tried many ways, here is my most recent code.
var done = document.createElement("button");
done.onClick=function() {
alert("working");
};
done.innerText = "Finished!";
done.id = "deleteButton_";
The button generates fine but nothing happens when clicked. Any ideas? Thanks!
case matters
done.onClick=function() {
needs to be
done.onclick=function() {
better if you use addEventListener and not all browsers support innerText look into textContent
For use addEventListener , you could do something like
done.addEventListener('click', function (){
alert('working');
});
var iDiv = document.createElement('div');
iDiv.id = 'buttonDiv';
var button= document.getElementById('buttonDiv').innerHtml('<input type="button" onclick="myFunction(this)"');
function myFunction(button){
console.log(buton.id);
alert('pressed button with id :'+button.id);
}
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.