将Jquery事件分配给动态按钮的最佳方法 [英] Best way to assign Jquery events to Dynamic buttons

查看:85
本文介绍了将Jquery事件分配给动态按钮的最佳方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在根据用户操作动态生成Twitter Bootstrap模态(长故事).可以说,有时用户可以在屏幕上看到100个模态.在每个模式中,我都有5个动态按钮,每个按钮都有自己的用途,并且在所有模式中都具有相同的功能,并且具有不同的ID.

I am generating twitter bootstrap modals dynamically based on the user action (Long Story). Lets say some times user can see 100 modals on his screen. In each and every modal I have 5 dynamic buttons, each have it own purpose and did same in all modals, and have different id's.

当有新的Twitter模式通过以下按钮ID打开时,我将使用jquery将onClick事件附加到这些按钮上

I am attaching onClick events to those buttons by using jquery when ever there is a new twitter modal opens up by using the button id as follows

$(document).on("click","#btn"+btnNumber, function(){
   //Code Goes Gere
});

因此,如果我打开100个模态,每个模态都有5个按钮,将点击事件分配500次是个好主意吗?

So If I open 100 modals, each have 5 buttons, Is it good idea to assigning click events for 500 times ?

或按如下所示使用其name属性1次来分配点击事件是一个好主意

or Is it good Idea to assign click events by using it's name attribute for 1 time as follows

$(document).ready(function(){
    $(document).on("click","btnNameAttr", function(){
       //Code Goes Gere
    });
});

推荐答案

jQuery on()可以帮助您.首先,您需要将DATA附加到元素ID(如btn+btnNumber).您可以在任何data-x属性(例如data-custom-info)中添加自定义信息,并使用jQuery attr('data-custom-info')语法检索信息.用on()方法注册的事件处理程序也可用于以后的元素(脚本执行后创建的元素).如下所示.

The jQuery on() can help you in this. First you need to detach appending DATA to your element ID like btn+btnNumber. You can add your custom information in any data-x attribute like data-custom-info and use the jQuery attr('data-custom-info') syntax to retrieve the information. The event handlers registered with on() method is also available for future elements(elements created after script execution). Like below.

创建新按钮时,将其添加为..

When creating new button, add render it as..

<input .... class="btnWithData" data-custom-info="1" ... />
<input .... class="btnWithData" data-custom-info="2" ... /> 

您的事件处理程序会变得如此.

and your event handler goes like..

$(document).ready(function(){
 $('body').on('click','.btnWithData',function(){
//DO WHATEVER
var buttonData=$(this).attr('data-custom-info');
//DO WHATEVER
 });
});

这篇关于将Jquery事件分配给动态按钮的最佳方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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