需要选中所有复选框并为每个复选框动态添加特定事件处理程序

编程入门 行业动态 更新时间:2024-10-24 12:23:13
本文介绍了需要选中所有复选框并为每个复选框动态添加特定事件处理程序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

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

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(); }); });

更多推荐

需要选中所有复选框并为每个复选框动态添加特定事件处理程序

本文发布于:2023-10-12 23:21:47,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1486176.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:复选框   并为   事件   程序   动态

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!