简体   繁体   中英

Bind to click-event to dynamically created button without selector

I'm trying to dynamically create elements using javascript and jQuery. Currently I'm stuck with binding a simple click-event to a dynamically created button-element.

The button is created with

var theButton = $("<button>...</button>");

Now I want to bind the click-event, so I added

theButton.on("click", function(){...}); // which is not working

Other solutions pointed out, that it must be bound to a container. So I ended up with

$(document).on("click", theButton, function(){...}); // this fires no matter where I click

The problem is the selector (2nd param of the on method) which is a jQuery-object at this point.

Also tried

theButton[0].onclick = () => alert("Clicked")

which is also not working

Try this. It's working

$(function(){
   var theButton = $("<button>button</button>");
   theButton.click(function(){
      alert('clicked');
   })
   $('body').append(theButton);
})

Working fiddle

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