添加一个onClick事件append() [英] Add an onClick event to append()
问题描述
我正在动态创建一个div。我想添加一个onClick()事件。
如何在< div class =中添加一个onClick id =btnHomeonClick =return true>
to this?
abc。 append(
$('< div />',{class:'something',id:'btnHome'})
);
编辑:
$('< div />',{class :'something',id:'btnHome'onClick:'return true'})
活动委托是正确的方式,@Tushar为您提供了答案。但是,如果您之后是这样的:
$('< div />',{class:'something ',id:'btnHome'onClick:'return true'})
然后,您可以:
$('< div />',{
'text':'new',$ b $('$'''''):'something',
'id':'btnHome'
})。on({$ b $'click':function(){alert(clicked)}
});
Demo @ 小提琴
由于斜视建议您在下面的评论之一中,也可以使用点击
作为参数,就像 text
或<$ c $
$('< div />',{c> id
'text':'new',
'class':'something',
'id':'btnHome',
'click':function(){alert( clicked)}
});
I'm dynamically creating a div. I'd like to add a onClick() event to it.
How do I add an onClick as in <div class="something" id="btnHome" onClick="return true">
to this?
abc.append(
$('<div />', { class: 'something', id: 'btnHome' })
);
EDIT:
I'm looking for an answer something like this
$('<div />', { class: 'something', id: 'btnHome' onClick: 'return true' })
Event delegation is the right way to do it and @Tushar has the answer for you. But, if you were after something like this:
$('<div />', { class: 'something', id: 'btnHome' onClick: 'return true' })
Then, you may do:
$('<div/>', {
'text': 'new',
'class': 'something',
'id': 'btnHome'
}).on({
'click': function() { alert ("clicked") }
});
Demo@Fiddle
As squint suggests in one of the comments below, you could also use click
as an attribue just like text
or id
as the following.
$('<div/>', {
'text': 'new',
'class': 'something',
'id': 'btnHome',
'click': function() { alert ("clicked") }
});
这篇关于添加一个onClick事件append()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!