I'm using labels for my form, like this :
我正在为我的表单使用标签,如下所示:
<label for="foo" id="bar">Label</label>
<input type="checkbox" id="foo" />
I want to hide an element when the user uncheck the box, and show it otherwise.
我想在用户取消选中该框时隐藏元素,否则显示该元素。
The problem is, if I bind the click event to "foo", it'll only works when the user clicks on the checkbox itself and not on the label. Therefore, do I also need to bind a click event on the label ? Or should I enclose both elements within a span ? My HTML already contains 2344 elements, so I'd like to do it without adding anything, and without doubling the JavaScript code or the selector, if possible.
问题是,如果我将click事件绑定到“foo”,它将仅在用户单击复选框本身而不是标签上时才有效。因此,我还需要在标签上绑定click事件吗?或者我应该将两个元素都包含在一个范围内?我的HTML已经包含2344个元素,所以我想在不添加任何内容的情况下执行此操作,并且如果可能的话,不要将JavaScript代码或选择器加倍。
2 个解决方案
#1
14
Instead of binding with the click()
event, you should bind using the change()
event, then however this change is triggered the outcome will be the same:
您应该使用change()事件绑定而不是与click()事件绑定,然后触发此更改,结果将是相同的:
$('#foo').change(
function(){
// do whatever
});
References:
#2
3
The change
event should fire for the input
whether the label
or input
is clicked:
无论是否单击标签或输入,都应触发change事件:
$("#foo").change(function () { ... });
#1
14
Instead of binding with the click()
event, you should bind using the change()
event, then however this change is triggered the outcome will be the same:
您应该使用change()事件绑定而不是与click()事件绑定,然后触发此更改,结果将是相同的:
$('#foo').change(
function(){
// do whatever
});
References:
#2
3
The change
event should fire for the input
whether the label
or input
is clicked:
无论是否单击标签或输入,都应触发change事件:
$("#foo").change(function () { ... });