繁体   English   中英

jQuery选中和取消选中复选框

[英]jQuery checking and unchecking checkboxes

我必须选中并取消选中复选框。 但是它不能很好地工作。

示例:当第一负载的状态为活动时:

  • 取消选中复选框为非活动状态(正常工作)
  • 再次检查以使其处于活动状态(不起作用,保持选中状态)

示例:在第一个负载上状态为非活动状态:

  • 选中复选框为活动状态(工作正常)
  • 取消选中复选框为非活动状态(正常工作)
  • 再次检查以使其处于活动状态(不起作用,保持选中状态)

这是我的示例代码:

var statusCheck = $('.status-box');

$.ajax({
    url: 'sample/url',
    type: 'POST',
    data: {
        user_id: ids,
        status: statusVal
    },
    success: function (response) {
        if (response == 'ok') {
            $.each(statusCheck, function () {
                var _this = $(this);

                if (_this.is(':checked')) {
                    _this.removeAttr('checked');
                } else {
                    _this.attr('checked', '');
                }
            });
        }
    }
});
var statusCheck = $('.status-box')

$.ajax({
        url     : 'sample/url',
        type    : 'POST',
        data    : { user_id: ids, status: statusVal },
        success : function( response ) {
            if( response == 'ok' ) {
                $.each(statusCheck, function(){
                    var _this    = $(this);

                    if( _this.is(':checked') ) {
                        _this.removeAttr('checked');
                    } else {
                        _this.attr('checked', 'checked');
                             // ...............^ here ^
                    }
                });
            }
        }
    });

试试这个: _this.attr('checked', 'checked');

同样,此链接中的 .prop()可能会.prop()神奇作用;)

我在使用JQuery选中和取消选中复选框时遇到了问题(奇怪的异常)。 我正在使用.attr.removeAttr ,当我将其更改为.prop('checked',false/true)我解决了该问题。

在jQuery 1.6之前,.attr()方法在检索某些属性时有时会考虑属性值,这可能会导致行为不一致。 从jQuery 1.6开始,.prop()方法提供了一种显式检索属性值的方法,而.attr()则检索属性。 参考:

注意您应该使用JQuery 1.6 +

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM