[英]How to fix javascript not working on newer jquery library but working on older version jquery library?
i have this javascript code whhich makes checkbox work as radio 我有这个JavaScript代码,使复选框可以作为收音机工作
JAVASCRIPT JAVASCRIPT
$(function() {$('input[type=checkbox]').click(function() {
$('input[type=checkbox]').attr('checked', false);
$(this).attr('checked', true);
});
});
HTML 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>
Which was working when i was using older jquery library of version 1.8.3 but when i tried to include the newer jquery library of version 1.11.0 , its not working, 当我使用版本1.8.3的较旧jquery库但在尝试包含版本1.11.0的较新jquery库时,该方法正常工作,
how can i fix it ? 我该如何解决?
here is http://jsfiddle.net/6upmbbf0/ 这是http://jsfiddle.net/6upmbbf0/
if you change the jquery version on top left to 1.8.3 or lower it works but above 1.8.3 it doesnt. 如果将左上方的jquery版本更改为1.8.3或更低,则它可以工作,但高于1.8.3则不行。
The correct method to retrieve and update a checkbox's checked state is .prop()
. 检索和更新复选框的选中状态的正确方法是
.prop()
。 The .attr()
simply retrieves or updates the attribute value; .attr()
只需检索或更新属性值; it does not necessarily update the underlying state of the input . 它不一定更新输入的基础状态 。
jQuery Core 1.9 upgrade guide mentions that behavior is changed, which explains why your code worked in jQuery < version 1.9. jQuery Core 1.9升级指南提到行为已更改,这说明了为什么您的代码在jQuery <1.9版中有效。
Use not()
instead of toggling the checkbox 2 times. 使用
not()
而不是两次切换复选框。 If you exclude the checked checkbox in the first place, and uncheck the others, it works better. 如果首先排除选中的复选框,然后取消选中其他复选框,则效果更好。
$('input[type=checkbox]').not($(this)).prop('checked', false);
fiddle: http://jsfiddle.net/6upmbbf0/3/ 小提琴: http : //jsfiddle.net/6upmbbf0/3/
edit, added suggestion by Salman A to use prop()
instead of attr()
编辑,添加了Salman A的建议以使用
prop()
而不是attr()
Use 'prop' Instead of 'attr' as 使用'prop'代替'attr'作为
replace code 替换代码
$(function() {$('input[type=checkbox]').click(function() {
$('input[type=checkbox]').prop('checked', false);
$(this).prop('checked', true);
});
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.