同时在标签和复选框上绑定 JavaScript jQuery 单击事件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9196386/
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
Bind JavaScript jQuery click event on label AND on checkbox simultaneously
提问by Willy
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.
问题是,如果我将点击事件绑定到“foo”,它只会在用户点击复选框本身而不是标签时起作用。因此,我还需要在标签上绑定点击事件吗?或者我应该将两个元素都包含在一个跨度内?我的 HTML 已经包含 2344 个元素,所以我想在不添加任何东西的情况下完成它,如果可能的话,也不要将 JavaScript 代码或选择器加倍。
回答by David says reinstate Monica
回答by Andrew Whitaker
The change
event should fire for the input
whether the label
or input
is clicked:
该change
事件应该针对或input
是否被点击而触发:label
input
$("#foo").change(function () { ... });