为什么我的复选框更改事件没有触发? [英] Why isn't my checkbox change event triggered?

查看:33
本文介绍了为什么我的复选框更改事件没有触发?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个功能.

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

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

问题是当我使用第一个函数选中/取消选中该框时,没有调用第二个函数.我是 JavaScript 新手,谢谢.

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.

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

推荐答案

change 事件不会在您以编程方式更改复选框的值时触发.您可以做些什么来确保它触发:

The change event 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();
    }
});

这篇关于为什么我的复选框更改事件没有触发?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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