I'm dynamically creating a div. I'd like to add a onClick() event to it.
How do I add an onClick as in EDIT: I'm looking for an answer something like this Event delegation is the right way to do it and @Tushar has the answer for you. But, if you were after something like this: Then, you may do: Demo@Fiddle As squint suggests in one of the comments below, you could also use Use Event delegation allows us to attach a single event listener, to a parent element, that will fire for all descendants matching a selector, whether those descendants exist now or are added in the future. For dynamically added elements use parent to add event to the added elements. You can also use see jQuery Docs for You can use delegated events so add to your jquery code: You can use document or any other parent element that is already in the DOMabc.append( $('', { class: 'something', id: 'btnHome' }) );
$('', { class: 'something', id: 'btnHome' onClick: 'return true' })
回答1:
$('', { class: 'something', id: 'btnHome' onClick: 'return true' })
$('', { 'text': 'new', 'class': 'something', 'id': 'btnHome' }).on({ 'click': function() { alert ("clicked") } });
click
as an attribue just like text
or id
as the following.$('', { 'text': 'new', 'class': 'something', 'id': 'btnHome', 'click': function() { alert ("clicked") } });
回答2:
event delegation
:
$(staticParentSelector).on('click', '.something', function () { // Event Handler Code here });
document
, but this costs performance$(document).on('click', '.something', function () { // Event Handler Code here });
on
回答3:
$(document).on('click','#btnhome',function(){'do something here'});