【问题标题】:Unable to control checkbox checked status - jquery无法控制复选框选中状态 - jquery
【发布时间】:2010-11-29 19:29:02
【问题描述】:

我无法通过这个 onClick 事件来控制复选框的选中状态。有什么想法吗?

        init: function () {
            $('.billing input[type="checkbox"]').bind('click', function (e) {
                e.preventDefault();
                iKeyless.page.toggleShippingForm($(e.currentTarget));
            });
        },
        toggleShippingForm: function (el) {
            if (el.attr('checked')) {
                $('.shipping').parents('.yui-u').addClass('hide');
                el.attr('checked', false);
            } else {
                $('.shipping').parents('.yui-u').removeClass('hide');
                el.attr('checked', true);
            }
        }

它会在选中复选框的情况下加载,无论我做什么,它都会保持选中状态......

【问题讨论】:

    标签: jquery


    【解决方案1】:

    应该只是传入this 来引用<input> 元素...虽然您不需要jQuery 对象,但这里有一个工作版本:

    init: function () {
        $('.billing input[type="checkbox"]').bind('click', function (e) {
            e.preventDefault();
            iKeyless.page.toggleShippingForm($(this));
        });
    },
    toggleShippingForm: function (el) {
        if (el.attr('checked')) {
            $('.shipping').parents('.yui-u').addClass('hide');
            el.attr('checked', false);
        } else {
            $('.shipping').parents('.yui-u').removeClass('hide');
            el.attr('checked', true);
        }
    }
    

    但由于 .checked 是一个 DOM 属性,您可以这样做(无需转换为 jQuery 对象):

    init: function () {
        $('.billing input[type="checkbox"]').change(function (e) {
            e.preventDefault();
            iKeyless.page.toggleShippingForm(this);
        });
    },
    toggleShippingForm: function (el) {
        $('.shipping').parents('.yui-u').toggleClass('hide', el.checked);
    }
    

    元素正在改变它的.checked 状态...只需在change 事件中使用它。如果需要,将 .toggleClass('hide', el.checked) 更改为 .toggleClass('hide', !el.checked),具体取决于它应该以哪种方式显示。

    【讨论】:

      猜你喜欢
      • 2015-12-15
      • 2011-07-01
      • 2023-03-05
      • 1970-01-01
      • 1970-01-01
      • 2011-03-08
      • 2012-06-29
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多