首页 文章

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

提问于
浏览
20

我有两个功能 .

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

问题是当我使用第一个函数来检查/取消选中该框时,不会调用第二个函数 . 我是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>

3 回答

  • 5

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

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

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

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

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


    第二个片段可以优化:

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

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

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

相关问题