动态添加点击事件复选框,只适用于第一个复选框JQUERY

Dynamically adding click event to checkbox, only works for first checkbox JQUERY

本文关键字:复选框 适用于 第一个 JQUERY 动态 事件 添加      更新时间:2023-09-26

所以我正在与每个控件上具有不同复选框区域的一对ascx一起工作。我最初使用

 $('[type=checkbox]').click ( function(){ code });

一开始确实起了作用。但是当我添加另一个控件时,也使用复选框,该函数也会触发其他复选框,所以我将js升级为

 $('#chck').click(function(){ code });

但是这样,它只会为列表中的第一个复选框触发一个事件。我怎样才能让它触发所有点击?

我也试过这个:

 $('#chck').each(function(){ $(this).click({ function() { code }); });

,这只适用于第一个

下面是我的ascx页面示例:

 <asp:Repeater ID="contacts" runat="server">
            <ItemTemplate>
                <tr>
                    <td>
                        <input type="checkbox" id="chck" />
                    </td>
                  .....
                 </tr>
             </ItemTemplate>
  </asp:Repeater>
这是我的JS代码段
    $(document).ready(function(){
       $("#chck").each(function () {
           $(this).click(function () { onchange($(this)); });
       });
    });
    function onchange(checkbox) {
    // adds contact to list
    }

id必须唯一。用类代替:

<input type="checkbox" class="chck" />
$('.chck').click(function(){ code });

参见using same ids for multiple elems on a same page is invalid.

IDs should be unique to each element. When this happens browser only selects first of it.

为了克服这个问题,必须将id更改为class。所以你have to do same thing with your markup change id to class:

<input type="checkbox" class="chck" /> // <----change id to class for every input
现在你的脚本应该是:
$('.chck').each(function(){ //<-----use '.' notation for class selectors 
     $(this).click(function() { 
         onchange($(this));
     }); 
});