JQuery 将单击事件绑定到复选框
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11235966/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
JQuery bind click event to checkboxes
提问by iJared
Here's a basic view of what my html looks like:
这是我的 html 外观的基本视图:
<form>
<div id="part1">
// some html form elements including checkboxes
</div>
<div id="part2">
// more html code with more checkboxes
</div>
<div id=part2">
// data table with numerous checkboxes built dynamically
</div
</form>
What I need to do is bind the .click()
event to the checkboxes in part 1, 2, and 3 seperately. I've tried this $('#part1:checkbox').click(...)
but that didn't work. If I use $("form :checkbox").click(...)
same click event is bound to all checkboxes and not just one set. How would I seperate these?
我需要做的是将.click()
事件分别绑定到第 1、2 和 3 部分中的复选框。我试过这个,$('#part1:checkbox').click(...)
但没有用。如果我使用$("form :checkbox").click(...)
相同的点击事件绑定到所有复选框,而不仅仅是一组。我将如何分离这些?
回答by Joseph Silber
You're almost there. You just need a space to separate the descendant selector:
您快到了。你只需要一个空格来分隔后代选择器:
$('#part1 :checkbox').click(function(){
// code goes here
});
To increase performance, you might wanna use this:
为了提高性能,你可能想使用这个:
$('#part1 input[type=checkbox]').click(function(){
// code goes here
});
回答by user3512003
Or you give same class name for all checkboxes and give the corresponding div ID for the checkbox also, so you can use the following code,
或者您为所有复选框提供相同的类名,并为复选框提供相应的 div ID,因此您可以使用以下代码,
<input type="checkbox" class="checkall" id="part1">Part 1
and your script goes like this.
你的脚本是这样的。
$('.checkall').click(function () {
if (this.checked == false) {
$("." + $(this).attr("id")).hide();
}
});
回答by Craig London
I had a similar issue, and this StackOverflow page is the first answer I stumbled upon, but wasn't really satisfied with it. I found this article https://www.kevinleary.net/jquery-checkbox-checked/with a better solution.
我有一个类似的问题,这个 StackOverflow 页面是我偶然发现的第一个答案,但并不真正满意。我发现这篇文章https://www.kevinleary.net/jquery-checkbox-checked/有一个更好的解决方案。
$('input[name="subscribe"]').on('click', function(){
if ( $(this).is(':checked') ) {
$('input[name="email"]').show();
}
else {
$('input[name="email"]').hide();
}
});