切换功能在jQuery 1.9.1+中按预期工作

时间:2015-01-05 16:18:06

标签: javascript jquery html

我正在使用jQuery来选择一个复选框列表。我正在使用这个小提琴中概述的代码:

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

http://jsfiddle.net/gubhaju/Vj6wY/3/

它在小提琴中工作,但不在我的网站上(按钮正在消失)。然后我看到小提琴使用版本1.4.4,而我的网站使用版本2.1.1。玩完小提琴后,我发现只有jQuery版本1.8.3及更低版本才是精选工作。 1.8.3和1.9.2之间有什么变化?如何修改此代码以使其适用于我的版本?

4 个答案:

答案 0 :(得分:2)

正如我在评论中向您展示的那样,您所引用的jQuery版本有很多变化。您可以使用jQuery Migrate插件(由jQuery团队制作)来帮助解决更改问题,但简而言之,您可以将代码简化为:

$('.check').click(function () {
    $('input:checkbox').prop('checked', !$('input:checkbox').prop('checked'));
    $(this).val(($(this).val() == 'uncheck all') ? 'check all' : 'uncheck all')
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="button" class="check" value="check all" />
<input type="checkbox" class="cb-element" />Checkbox 1
<input type="checkbox" class="cb-element" />Checkbox 2
<input type="checkbox" class="cb-element" />Checkbox 3

答案 1 :(得分:1)

以下是您在较新版本中使用的可能解决方法(尽可能保持原始代码完整)

JSFiddle

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

请注意,您还必须使用prop()代替attr()来设置已选中。

答案 2 :(得分:1)

还有一种可行的解决方法:

$('.check:button').click(function () {
    var toggled = this.value == 'check all';
    $('input:checkbox').prop('checked', toggled);
    this.value = toggled ? 'uncheck all' : 'check all';
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="button" class="check" value="check all" />
<input type="checkbox" class="cb-element" />Checkbox 1
<input type="checkbox" class="cb-element" />Checkbox 2
<input type="checkbox" class="cb-element" />Checkbox 3

答案 3 :(得分:0)

你的toggle(Function, Function) no longer exists来自jQuery 1.9以上。

您可以使用简单变量来跟踪状态来恢复功能:

$(document).ready(function(){
var state = 1;
    $('.check:button').click(function(){
        if (state) {
            $('input:checkbox').attr('checked','checked');
            $(this).val('uncheck all')
        } else {
            $('input:checkbox').removeAttr('checked');
            $(this).val('check all');
        }
        state = !state;
    });
});
相关问题