jQuery升级导致切换不再起作用

时间:2014-05-07 20:13:08

标签: jquery checkbox toggle

小提琴http://jsfiddle.net/hdD8B/

我无法替换在jQuery 1.7中运行的代码。

我有一个按钮,只需在点击时检查所有复选框,然后在再次点击时取消选中它们。

    $('.check:button').toggle(
        function () {
        $('input:checkbox').attr('checked', 'checked');
        $(this).val('uncheck all');
    }, function () {
        $('input:checkbox').removeAttr('checked');
        $(this).val('check all');
    });

这是我能够得到的最接近它的工作来检查和取消选中一次然后再也不起作用了。将一个简单的方法替换为更复杂的方法似乎也很难看。

(function ($) {
    $.fn.clickToggle = function (func1, func2) {
        var funcs = [func1, func2];
        this.data('toggleclicked', 0);
        this.click(function () {
            var data = $(this).data();
            var tc = data.toggleclicked;
            $.proxy(funcs[tc], this)();
            data.toggleclicked = (tc + 1) % 2;
        });
        return this;
    };
}(jQuery));

/*global $, jQuery,document,fnCreateSelect*/
$(document).ready(function () {





    $('.check:button').clickToggle(
        function () {
        $('input:checkbox').attr('checked', 'checked');
        $(this).val('uncheck all');
    }, function () {
        $('input:checkbox').removeAttr('checked');
        $(this).val('check all');
    });

1 个答案:

答案 0 :(得分:1)

正如您可能已经阅读过的那样,在jQuery 1.8之后删除了.toggle() -

  

注意:此方法签名在jQuery 1.8中已弃用,在jQuery 1.9中已删除。 jQuery还提供了一个名为.toggle()的动画方法,可以切换元素的可见性。是否触发动画或事件方法取决于传递的参数集。 http://api.jquery.com/toggle-event/

以下是解决问题的一种方法 -

$('.check:button').click(function () {
    if('check all' == $(this).val() ) {
        $('input:checkbox').prop('checked', true);
        $(this).val('uncheck all');
    } else {
        $('input:checkbox').prop('checked', false);
        $(this).val('check all');
    }
});

你会注意到我切换到prop()而不是attr(),因为prop()被认为是这样的元素的时尚。关于“最佳实践”的争论很多但是这篇文章很好地阅读 - .prop() vs .attr()