jquery - jQuery 中 prop() 和 attr() 的区别以及何时使用 attr() 和 prop()

标签 jquery attr prop

<分区>

我在某些地方看到 .attr() 在 jQuery 中使用。在某些地方使用 .prop()。但我搜索了 在 SO 和谷歌中我很困惑。请告诉我两者之间的确切区别 这两个以及何时使用它们。

我看过以下链接 jQuery attr vs. prop, there are a list of props? jQuery attr vs prop?

但我没有得到答案。请帮助我。在此先感谢。

在投反对票之前请说明原因,然后我会在下一篇文章中更正。

最佳答案

来自 docs

The difference between attributes and properties can be important in specific situations. Before jQuery 1.6, the .attr() method sometimes took property values into account when retrieving some attributes, which could cause inconsistent behavior. As of jQuery 1.6, the .prop() method provides a way to explicitly retrieve property values, while .attr() retrieves attributes.

例子

For example, selectedIndex, tagName, nodeName, nodeType, ownerDocument, defaultChecked, and defaultSelected should be retrieved and set with the .prop() method. Prior to jQuery 1.6, these properties were retrievable with the .attr() method, but this was not within the scope of attr. These do not have corresponding attributes and are only properties.

评论后更新

您可以为 HTML 元素设置一个属性。您在编写源代码时定义它,一旦浏览器解析您的代码,将创建相应的 DOM 节点,该节点是一个具有属性的对象。

简单的例子可以是..

<input type="test" value="test" id="test" />

这里的type, value, id是属性。一旦浏览器渲染它,你就会得到其他属性,比如align, alt, autofocus, baseURI, checked等等。

link如果你想阅读更多内容

关于jquery - jQuery 中 prop() 和 attr() 的区别以及何时使用 attr() 和 prop(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16051491/

相关文章:

asp.net - 我正在考虑将 ASP.Net Ajax ScriptManager Javascript 迁移到 JQuery,我需要注意什么?

javascript - 在自定义大小弹出窗口中打开任何链接的最佳轻量级不显眼解决方案是什么?

jquery - 为什么 jQuery 显示此属性为未定义?

javascript - 使用 jQuery 获取多个属性 (Src)

javascript - 测试客户端是否支持 css prop。重复后代码中断

javascript - 使用 jQuery 将图像链接更改为 "#"

javascript - 无法使用 jQuery 更改 svg 颜色

javascript - 隐藏其他 Accordion 项目

jquery在src更改后获取图像宽度

javascript - jQuery:如果选中则禁用 Prop