【问题标题】:Best way to assign Jquery events to Dynamic buttons将 Jquery 事件分配给动态按钮的最佳方法
【发布时间】:2014-03-29 21:30:54
【问题描述】:

我正在根据用户操作动态生成 twitter 引导模式(长篇故事)。假设有时用户可以在他的屏幕上看到 100 个模态。在每个模态中,我都有 5 个动态按钮,每个按钮都有自己的用途,并且在所有模态中都具有相同的功能,并且具有不同的 id。

当有一个新的推特模式打开时,我会使用 jquery 将 onClick 事件附加到这些按钮,如下所示

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

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

或者通过使用它的名称属性1次来分配点击事件是个好主意,如下所示

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

【问题讨论】:

标签: javascript jquery performance twitter-bootstrap


【解决方案1】:

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

创建新按钮时,添加渲染为..

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

你的事件处理程序就像..

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

【讨论】:

  • 我认为你的 on 参数颠倒了,它应该是 .on('event', 'selector', handler)。 api.jquery.com/on 你在选择器中有两个句点而不是一个句点:)
  • 是的,没错。对于那个很抱歉。感谢您指出这一点。
【解决方案2】:

您应该按照@Ananthan-Unni 的建议使用jQuery.on() 方法分配委派事件侦听器,但格式为:

$.on('click', 'button', listener)    

在这种情况下,您不需要分配唯一的 ID 或属性。您可以使用标签名称或类名称作为选择器(第二个参数)。

看看这里:https://api.jquery.com/on/ 并阅读委托活动

【讨论】:

    【解决方案3】:

    最好不要使用需要内存的闭包。改用良好的旧数据标签:

    $(document).ready(function () {
      $("#wrapper").on("click", "btnNameAttr", function () {
        var n;
    
        n = $(this).data("number");
        // code goes here
      });
    });
    

    要区分#wrapper 中实际点击的元素,请使用data-number 属性,如下所示:

    <div id="wrapper">
      <img data-number="000" />
      <img data-number="001" />
      <img data-number="002" />
      <img data-number="003" />
    </div>
    

    此代码将执行得更好,并且您仍然可以通过使用包装 &lt;div&gt; 元素和 data-number="" 属性来获得所需的所有功能。而且您不会干扰您可能已经在这些元素上拥有的 classid 属性。

    您甚至可以将命令添加到标签中:

    <img data-number="000" data-command="edit" />
    <img data-number="000" data-command="show" />
    <img data-number="000" data-command="delete" />
    

    然后打开它:

    switch ($(this).data("command"))
    {
      case "edit":
        // edit element with number n here
        break;
    }
    

    【讨论】:

      猜你喜欢
      • 2014-03-29
      • 2011-10-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多