如何修复javascript在较新的jquery库上运行,但在较旧版本的jquery库上运行

How to fix javascript not working on newer jquery library but working on older version jquery library?

本文关键字:运行 jquery 版本 javascript 何修复      更新时间:2023-09-26

我有这个JavaScript代码,使复选框作为收音机工作

JAVASCRIPT

$(function() {$('input[type=checkbox]').click(function() {
        $('input[type=checkbox]').attr('checked', false);
        $(this).attr('checked', true);
    });
});

.HTML

<label title="cat"><input name="" type="checkbox" checked>cat</label>
<label title="dog"><input name="" type="checkbox" >dog</label>
<label title="lion"><input name="" type="checkbox" >lion</label>
<label title="fish"><input name="" type="checkbox" >fish</label>
<label title="turtle"><input name="" type="checkbox" >turtle</label>

当我使用 1.8.3 版的旧 jquery 库时,它正在工作但是当我尝试包含版本 1.11.0 的较新的 jquery 库时,它不起作用,

我该如何解决它?

这是 http://jsfiddle.net/6upmbbf0/

如果您将左上角的 jQuery 版本更改为 1.8.3 或更低版本,它可以工作,但在 1.8.3 以上则不起作用。

检索和更新复选框的选中状态的正确方法是.prop().attr()只是检索或更新属性值;它不一定更新输入的基础状态


jQuery Core 1.9 升级指南提到行为发生了变化,这解释了为什么你的代码在 jQuery <1.9 版本中工作。

使用not()而不是切换复选框 2 次。如果您首先排除选中的复选框,然后取消选中其他复选框,则效果更好。

$('input[type=checkbox]').not($(this)).prop('checked', false);

小提琴:http://jsfiddle.net/6upmbbf0/3/

编辑,添加了萨尔曼 A 的建议,使用 prop() 而不是attr()

使用 '

prop' 而不是 'attr' 作为

替换代码

$(function() {$('input[type=checkbox]').click(function() {
        $('input[type=checkbox]').prop('checked', false);
        $(this).prop('checked', true);
    });
});