jQuery HTML - 属性与属性
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19246714/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
HTML - attributes vs properties
提问by JS-
Is id
an attribute or property of HTML?
是id
HTML 的属性还是属性?
should I do $('#selector').attr('id');
or $('#selector').prop('id');
我应该做$('#selector').attr('id');
还是$('#selector').prop('id');
I've read many articles and am still confused.
看了很多文章,还是一头雾水。
Could someone please explain to me what the differences between attributes & properties in HTML/JS are in very simple language?
有人可以用非常简单的语言向我解释 HTML/JS 中的属性和属性之间的区别吗?
回答by Quentin
Attributes are defined by HTML. Properties (on DOM elements) are defined by DOM (and also HTML 5 which blurs the boundary between markup and DOM).
属性由 HTML 定义。属性(在 DOM 元素上)由 DOM 定义(还有 HTML 5,它模糊了标记和 DOM 之间的边界)。
Some HTML attributes have 1:1 mapping onto properties. id
is one example of such.
一些 HTML 属性具有到属性的 1:1 映射。id
就是这样的一个例子。
Sometimes the names are different. The class
attribute maps onto the className
property, and the value
attribute maps on to the defaultValue
property (while the value
property has no corresponding attribute).
有时名称不同。的class
属性映射到className
属性和value
属性映射到defaultValue
属性(当value
属性没有对应的属性)。
When I originally wrote this answer, I thought there were attributes without a 1:1 mapping to a property. With this update, I can no longer think of any (and have made corrections for the above examples).
当我最初写这个答案时,我认为存在没有 1:1 映射到属性的属性。有了这个更新,我再也想不起来了(并且对上面的例子做了更正)。
回答by Anand Jha
Yes, attr is meant for html attributes as they are strictly defined. prop is for properties.
是的,attr 用于 html 属性,因为它们是严格定义的。prop 用于属性。
So for instance, say you have a node elem with class "something" (raw element not jQuery object). elem.className is the property, but is where the attribute resides. Changing the class attribute also changes the property automatically and vise versa.
例如,假设您有一个节点元素,其类为“something”(原始元素不是 jQuery 对象)。elem.className 是属性,但它是属性所在的位置。更改类属性也会自动更改属性,反之亦然。
Currently, attr is jumbled and confusing because it has tried to the job of both functions and there are many bugs because of that. The introduction of jQuery.fn.prop will solve several blockers, separate code as it should have been separated from the beginning, and give developers faster functions to do what they expect them to do.
目前,attr 是混乱和混乱的,因为它尝试了这两个功能的工作,因此存在许多错误。jQuery.fn.prop 的引入将解决几个障碍,分离代码,因为它应该从一开始就分开,并为开发人员提供更快的功能来完成他们期望他们做的事情。
Let me make up a percentage for a sec and say that from my experience in the support IRC and reading other's code, 95% of the use cases for attr will not have to switch to prop.
让我补一个百分比,然后说根据我在支持 IRC 和阅读其他代码方面的经验,attr 的 95% 用例将不必切换到 prop。