同时绑定JavaScript和on checkbox上的JavaScript jQuery click事件 [英] Bind JavaScript jQuery click event on label AND on checkbox simultaneously

查看:237
本文介绍了同时绑定JavaScript和on checkbox上的JavaScript jQuery click事件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我为我的表单使用标签,如下所示:

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.

问题是,如果我将点击事件绑定到foo,它只会在用户单击复选框而不是标签上时才会生效。因此,我还需要绑定标签上的点击事件吗?或者我应该在一个范围内包围这两个元素?
我的HTML已经包含2344个元素,所以我不想添加任何东西,如果可能的话,没有加倍JavaScript代码或选择器。

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()事件,应该使用 change code>事件,然而这个改变被触发的结果将是相同的:

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:

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

参考文献:

这篇关于同时绑定JavaScript和on checkbox上的JavaScript jQuery click事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆