Javascript 为什么我的复选框更改事件没有触发?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4869981/
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-08-23 14:31:58  来源:igfitidea点击:

Why isn't my checkbox change event triggered?

javascriptjqueryhtmlcheckboxclick

提问by sxv

I have two functions.

我有两个功能。

The first function translates a div click into a checked/unchecked toggle. The second function translates a checkbox change into a hide/show event.

第一个函数将 div 单击转换为选中/未选中的切换。第二个函数将复选框更改转换为隐藏/显示事件。

The problem is that when I use the first function to check/uncheck the box, the second function is not called. I am new to javascript, thanks.

问题是,当我使用第一个函数选中/取消选中该框时,不会调用第二个函数。我是 javascript 新手,谢谢。

<script type="text/javascript">
$(document).ready(function() {
    $(":checkbox").parent().click(function(evt) {
        if (evt.target.type !== 'checkbox') {
            var $checkbox = $(":checkbox", this);
            $checkbox.attr('checked', !$checkbox.attr('checked'));
            evt.stopPropagation();
            return false;
        }
    });
});
</script>

<script type="text/javascript">
$(document).ready(function() {
    $(":checkbox").change(function() {
        if($(this).attr("checked")) {
            $('.'+this.id).show();
        }
        else {
            $('.'+this.id).hide();
        }
    });
});
</script>

回答by Matthew Manela

The changeevent does not fire when you programmatically change the value of a check box. What you can do to ensure it fires is:

变化,当您以编程方式更改一个复选框的值不会触发事件。您可以做的是确保它着火:

 $(":checkbox").parent().click(function(evt) {
    if (evt.target.type !== 'checkbox') {
        var $checkbox = $(":checkbox", this);
        $checkbox.attr('checked', !$checkbox.attr('checked'));
        $checkbox.change();
    }
});

回答by ?ime Vidas

Don't bother with the first snippet. Just use LABEL elements:

不要打扰第一个片段。只需使用 LABEL 元素:

<label><input type="checkbox">Some option</label>

Now, when the user clicks the label (the text next to the checkbox), the checkbox will be activated.

现在,当用户单击标签(复选框旁边的文本)时,复选框将被激活。



The second snippet can be optimized:

可以优化第二个代码段:

$('input:checkbox').change(function() {
    $('#' + this.id).toggle(this.checked);
});

回答by Victor

you are using '.'which is for class selectors instead use '#'since you are using the element ID. Like this:

您正在使用'.'which 用于类选择器而不是使用,'#'因为您使用的是元素 ID。像这样:

$(document).ready(function() {
    $(":checkbox").bind('change', function() {
        if($(this).attr("checked")) {
            $('#'+this.id).show();
        }
        else {
            $('#'+this.id).hide();
        }
    });
});