0

所以我正在使用几个 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
    }
4

2 回答 2

3

ids 必须是唯一的。改用一个类:

<input type="checkbox" class="chck" />
$('.chck').click(function(){ code });
于 2013-03-08T17:51:23.110 回答
1

见上using same ids for multiple elems_same page is invalid.

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

要克服这个问题,必须更改idclass. 所以你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));
     }); 
});
于 2013-03-08T18:00:44.703 回答