同时在标签和复选框上绑定 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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 05:54:18  来源:igfitidea点击:

Bind JavaScript jQuery click event on label AND on checkbox simultaneously

javascriptjqueryhtmlcheckboxlabel

提问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

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:

click()您应该使用change()事件绑定而不是使用事件绑定,然后触发此更改,结果将相同:

$('#foo').change(
    function(){
        // do whatever
    });

References:

参考:

回答by Andrew Whitaker

The changeevent should fire for the inputwhether the labelor inputis clicked:

change事件应该针对或input是否被点击而触发:labelinput

$("#foo").change(function () { ... });

Examplehttp://jsfiddle.net/andrewwhitaker/6LMXW/

示例http://jsfiddle.net/andrewwhitaker/6LMXW/