[英]how to apply function to each checkbox on page?
I am trying to apply a function to every checkbox on a page that shows/hides <div class="selectlist">
depending on if the checkbox is checked, this function makes all the <div class="selectlist">
on the page toggle 我试图将一个功能应用于显示/隐藏<div class="selectlist">
的页面上的每个复选框,具体取决于是否选中了该复选框,此功能使页面上的所有<div class="selectlist">
$("input[type=checkbox]").live('change', function() {
if ($(this).is(':checked') == false) {
$('#selectlist').hide();
} else {
$('#selectlist').show();
}
});
I tried the jquery each
function like this but that doesnt seem to work 我尝试了jQuery这样的each
函数,但这似乎不起作用
$.each($("input[type=checkbox]").live('change', function() {
if ($(this).is(':checked') == false) {
$('#selectlist').hide();
} else {
$('#selectlist').show();
}
}));
I know its possible to this by using a class
instead of input[type=checkbox]
but I want to avoid doing that 我知道通过使用class
而不是input[type=checkbox]
可以做到这一点,但我想避免这样做
How can I make jquery change the behavior of the checkbox the user clicks? 如何使jquery更改用户单击的复选框的行为?
If you're trying to bind an event handler to all elements verifying input[type=checkbox]
, simply do 如果您尝试将事件处理程序绑定到所有验证input[type=checkbox]
元素,则只需执行
$(document).on('change', "input[type=checkbox]", function() {
if (!this.checked) {
$('#selectlist').hide();
} else {
$('#selectlist').show();
}
});
No need to use each
there : most jQuery functions work if the jQuery set contains more than one element. 无需在那里使用each
:如果jQuery集包含多个元素,则大多数jQuery函数each
可以使用。
Note that I use on
there instead of live
: after having been deprecated for a long time, live
has been removed from recent versions of jQuery. 请注意,我on
此处使用而不是live
:在长时间不赞成使用之后, live
已从最新版本的jQuery中删除。
EDIT : discussion in comments below lead to this code : 编辑:下面的注释中的讨论导致此代码:
$(document).on('change', "input[type=checkbox]", function() {
$(this).next().toggle(this.checked);
});
$(document).on('change', 'input[type=checkbox]', function() {
$('#selectlist').toggle(this.checked);
});
ID's are uniqe , and there is no "all the <div id="selectlist">
on the page toggle", there can be only one? ID是uniqe ,并且没有“页面切换上的所有<div id="selectlist">
”,只能有一个? Use a class instead, and show us what the markup looks like ! 请改用一个类,然后向我们展示标记的样子!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.