需要选中所有复选框并为每个复选框动态添加特定事件处理程序 [英] Need to select all checkboxes and dynamically add specific event handler to each

查看:129
本文介绍了需要选中所有复选框并为每个复选框动态添加特定事件处理程序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

鉴于页面中的以下重复标记:

Given the following repeated markup in a page:

<div>
     <input type="checkbox" id="chk1" />
     <div id="div1" >
          //stuff to toggle
     </div>
</div>
<div>
     <input type="checkbox" id="chk2" />
     <div id="div2" >
          //stuff to toggle
     </div>
</div>

如何获取所有复选框,然后在事件处理程序中为每个复选框动态添加切换到复选框?

How can I get all checkboxes and then dynamically add toggle to the associated div in an event handler for each checkbox?

$(document).ready(function() {
     $('input:checkbox').each(
          function() {
               $(this).bind('click", function() {
                    //Attach toggle() to associate DIV
                    //$('#div1').toggle();
               });
          });
});

有没有一种简单的方法可以做到这一点而不需要解析或假设有序的ID列表?

Is there a simple way to do this without resorting to either parsing or assuming an ordered list of IDs?

推荐答案


  • 使用更改事件,因为这真的是你关心的事情

  • 使用 .live()所以你只绑定1个监听器,而不是每个复选框1个

  • 使用DOM遍历找到< div>

    • Use the change event, since that's really what you care about
    • Use .live() so you only bind 1 listener, rather than 1 per checkbox
    • Use DOM traversal to find the <div>

      $(function ()
      {
          $('input:checkbox').live('change', function ()
          {
              $(this).next().toggle();
          });
      });
      


    • 这篇关于需要选中所有复选框并为每个复选框动态添加特定事件处理程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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