【问题标题】:JQMIGRATE: jQuery.fn.attr('selected') may use property instead of attributeJQMIGRATE:jQuery.fn.attr('selected') 可以使用属性而不是属性
【发布时间】:2015-04-10 08:54:51
【问题描述】:
$('#operatordelivery').attr('checked', true);

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

【问题讨论】:

标签: javascript jquery


【解决方案1】:

来自 JQMIGRATE 文档:

JQMIGRATE:jQuery.fn.attr('selected') 可以使用属性而不是属性

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

解决方案:一般不应将布尔属性传递给 $().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()difference between prop() and attr() in jQuery and when to use attr() and prop()

【讨论】:

  • 我读出了文件,但我仍然无法清楚地了解这个警告。如果我能从好的例子中得到答案会更有帮助。
  • @SasiDunston 检查编辑,添加更多资源,这是一个深入解释的变化
【解决方案2】:

使用 Jquery 版本 1.9.1+ 而不是

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

你必须使用这个

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

还有,而不是

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

你必须使用:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-08-23
    • 2022-11-27
    • 1970-01-01
    • 1970-01-01
    • 2022-01-04
    • 1970-01-01
    • 2021-01-11
    • 2012-11-16
    相关资源
    最近更新 更多