将onClick事件添加到动态生成的按钮? [英] Adding onClick event to dynamically generated buttons?
问题描述
< script>
for(i = 0; i< something.length; i ++){
$('body')。append('< button id =btnInit'+ i +'>'+ i + '< /按钮>');
}
< / script>
我不想为每个按钮创建一个唯一的onClick函数。我该如何做一个适用于所有人的单一方法。例如在按下时显示其标签文本。 使用称为事件冒泡的Javascript特性可以做到这一点。在这种情况下,您可以将点击
处理程序附加到 body
元素以及这些按钮上的所有点击都将触发事件处理程序。在jQuery中最好的方法是使用 < / a>方法:
$(document.body).on('click','button',function(){
alert('button'+ this.id +'clicked');
});
无论元素何时创建 - 元素创建之前或之后都可以使用。 p>
这与
,效率和灵活性要低得多。
in Javascript .. If I have a dynamically generated buttons and I want a generic onClick function. How can I do that ?
<script>
for(i=0;i<something.length;i++){
$('body').append('<button id="btnInit'+i+'" >'+i+'</button>');
}
</script>
I don't want to create a unique onClick function for each button. How can I do a single one that applies to all. e.g display its label text when pressed.
You can do this by using a Javascript feature called "event bubbling". Ancestor elements are notified of events on their descendent elements.
In this case, you can attach a click
handler to the body
element and all clicks on those buttons will trigger an event handler. The nicest way to do this in jQuery is to use the on
method:
$(document.body).on('click', 'button', function() {
alert ('button ' + this.id + ' clicked');
});
This will work no matter when the elements are created – before or after the elements were created.
This does exactly the same thing as the live
method, but live
uses on
behind the scenes and is far less efficient and flexible.
这篇关于将onClick事件添加到动态生成的按钮?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!