Need to select all checkboxes and dynamically add specific event handler to each
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 t开发者_Go百科oggle 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();
});
});
});
Is there a simple way to do this without resorting to either parsing or assuming an ordered list of IDs?
- 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(); }); });
You don't need the each()
or bind()
:
$('input:checkbox').click(function (event) {
//... using $(this)
});
精彩评论