将onClick事件添加到动态生成的按钮? [英] Adding onClick event to dynamically generated buttons?

查看:98
本文介绍了将onClick事件添加到动态生成的按钮?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Javascript中如果我有一个动态生成的按钮,我想要一个通用的onClick函数。我该怎么做?

 < 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>

这与 live 方法完全相同,但 live 在幕后使用 ,效率和灵活性要低得多。


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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆