JQMIGRATE:jQuery.fn.attr(’selected’)可能使用property而不是attribute

$('#operatordelivery').attr('checked', true); 

嗨,我目前正致力于将jQuery版本迁移到jQuery-2.1.1,我可以在控制台中看到警告JQMIGRATE: jQuery.fn.attr('selected') may use property instead of attribute 。 我没有清楚地知道这个警告解释了什么。 有人能告诉我这个错误是什么意思吗?

来自JQMIGRATE文档:

JQMIGRATE:jQuery.fn.attr(’selected’)可能使用property而不是attribute

原因 :在jQuery 1.9之前,$()。attr(“checked”)等有时会在与非XML元素交互时使用checked | selected属性而不是属性,尽管浏览器和HTML规范允许属性(当前状态)与属性(初始/默认状态)不同。 这是早期版本的jQuery的延续,它没有提供$()。prop。

解决方案 :布尔属性通常不应传递给$()。attr; 替换为$()。prop,除非您真的打算更新基础HTML属性。

参考: https : //github.com/jquery/jquery-migrate/blob/1.x-stable/warnings.md#jqmigrate-jqueryfnattrselected-might-use-property-instead-of-attribute

在特定情况下,属性和属性之间的差异可能很重要。 在jQuery 1.6之前,.attr()方法有时在检索某些属性时会考虑属性值,这可能会导致行为不一致。 从jQuery 1.6开始,.prop()方法提供了一种显式检索属性值的方法,而.attr()则检索属性。

jQuery文档: http : //api.jquery.com/prop/

SO: .prop()vs .attr()的参考答案以及jQuery中prop()和attr()之间的区别以及何时使用attr()和prop()

使用Jquery版本1.9.1+而不是

 $('#operatordelivery').attr('checked', true); $('#operatordelivery').attr('checked', 'checked'); 

你必须使用这个

 $('#operatordelivery').prop('checked', true); 

而且,而不是

 $('#operatordelivery').attr('checked') 

你必须使用:

 $('#operatordelivery').prop('checked')