Javascript HTML 中的属性和属性有什么区别?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6003819/
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
What is the difference between properties and attributes in HTML?
提问by schalkneethling
After the changes made in jQuery 1.6.1, I have been trying to define the difference between properties and attributes in HTML.
在 jQuery 1.6.1 中进行更改后,我一直试图在 HTML 中定义属性和属性之间的区别。
Looking at the list on the jQuery 1.6.1 release notes(near the bottom), it seems one can classify HTML properties and attributes as follows:
查看jQuery 1.6.1 发行说明(靠近底部)上的列表,似乎可以将 HTML 属性和属性分类如下:
Properties: All which either has a boolean value or that is UA calculated such as selectedIndex.
Attributes: 'Attributes' that can be added to a HTML element which is neither boolean nor containing a UA generated value.
属性:所有具有布尔值或 UA 计算的属性,例如 selectedIndex。
属性:可以添加到既不是布尔值也不包含 UA 生成值的 HTML 元素的“属性”。
Thoughts?
想法?
回答by ?ime Vidas
When writing HTML source code, you can define attributeson your HTML elements. Then, once the browser parses your code, a corresponding DOM node will be created. This node is an object, and therefore it has properties.
在编写 HTML 源代码时,您可以在 HTML 元素上定义属性。然后,一旦浏览器解析您的代码,就会创建一个相应的 DOM 节点。这个节点是一个对象,因此它有属性。
For instance, this HTML element:
例如,这个 HTML 元素:
<input type="text" value="Name:">
has 2 attributes (type
and value
).
有 2 个属性 (type
和value
)。
Once the browser parses this code, a HTMLInputElementobject will be created, and this object will contain dozens of properties like: accept, accessKey, align, alt, attributes, autofocus, baseURI, checked, childElementCount, childNodes, children, classList, className, clientHeight, etc.
一旦浏览器解析了这段代码,就会创建一个HTMLInputElement对象,这个对象将包含几十个属性,如:accept、accessKey、align、alt、attributes、autofocus、baseURI、checked、childElementCount、childNodes、children、classList、className、客户端高度等
For a given DOM node object, properties are the properties of that object, and attributes are the elements of the attributes
property of that object.
对于给定的 DOM 节点对象,属性是该对象的属性,属性是该对象属性的元素attributes
。
When a DOM node is created for a given HTML element, many of its properties relate to attributes with the same or similar names, but it's not a one-to-one relationship. For instance, for this HTML element:
当为给定的 HTML 元素创建 DOM 节点时,它的许多属性都与具有相同或相似名称的属性相关,但这不是一对一的关系。例如,对于这个 HTML 元素:
<input id="the-input" type="text" value="Name:">
the corresponding DOM node will have id
,type
, and value
properties (among others):
相应的 DOM 节点将具有id
、type
和value
属性(等等):
The
id
property is a reflected propertyfor theid
attribute: Getting the property reads the attribute value, and setting the property writes the attribute value.id
is a purereflected property, it doesn't modify or limit the value.The
type
property is a reflected propertyfor thetype
attribute: Getting the property reads the attribute value, and setting the property writes the attribute value.type
isn't a pure reflected property because it's limited to known values(e.g., the valid types of an input). If you had<input type="foo">
, thentheInput.getAttribute("type")
gives you"foo"
buttheInput.type
gives you"text"
.In contrast, the
value
property doesn't reflect thevalue
attribute. Instead, it's the current valueof the input. When the user manually changes the value of the input box, thevalue
property will reflect this change. So if the user inputs"John"
into the input box, then:theInput.value // returns "John"
whereas:
theInput.getAttribute('value') // returns "Name:"
The
value
property reflects the currenttext-content inside the input box, whereas thevalue
attribute contains the initialtext-content of thevalue
attribute from the HTML source code.So if you want to know what's currently inside the text-box, read the property. If you, however, want to know what the initial value of the text-box was, read the attribute. Or you can use the
defaultValue
property, which is a pure reflection of thevalue
attribute:theInput.value // returns "John" theInput.getAttribute('value') // returns "Name:" theInput.defaultValue // returns "Name:"
的
id
属性是一个反射属性的id
属性:获取属性读取的属性值,并且设置属性写入的属性值。id
是一个纯粹的反射属性,它不会修改或限制值。的
type
属性是一个反射属性的type
属性:获取属性读取的属性值,并且设置属性写入的属性值。type
不是纯粹的反射属性,因为它仅限于已知值(例如,输入的有效类型)。如果你有<input type="foo">
,那么theInput.getAttribute("type")
给你"foo"
但theInput.type
给你"text"
。相反,
value
属性不反映value
属性。相反,它是输入的当前值。当用户手动更改输入框的值时,该value
属性会反映此更改。所以如果用户"John"
在输入框中输入,那么:theInput.value // returns "John"
然而:
theInput.getAttribute('value') // returns "Name:"
该
value
属性反映输入框中的当前文本内容,而该value
属性包含来自 HTML 源代码的属性的初始文本内容value
。因此,如果您想知道当前文本框中的内容,请阅读该属性。但是,如果您想知道文本框的初始值是什么,请阅读该属性。或者您可以使用
defaultValue
属性,它是属性的纯反射value
:theInput.value // returns "John" theInput.getAttribute('value') // returns "Name:" theInput.defaultValue // returns "Name:"
There are several properties that directly reflect their attribute (rel
, id
), some are direct reflections with slightly-different names (htmlFor
reflects the for
attribute, className
reflects the class
attribute), many that reflect their attribute but with restrictions/modifications (src
, href
, disabled
, multiple
), and so on. The speccovers the various kinds of reflection.
有几个属性直接反映了它们的属性(rel
, id
),有些是名称略有不同的直接反映(htmlFor
反映了for
属性,className
反映了class
属性),许多反映了它们的属性但有限制/修改(src
, href
, disabled
, multiple
),等等在。该规范涵盖了各种反射。
回答by subtleseeker
After reading Sime Vidas's answer, I searched more and found a very straight-forward and easy-to-understand explanation in the angular docs.
在阅读了Sime Vidas的回答后,我进行了更多搜索,并在angular docs 中找到了一个非常直接且易于理解的解释。
HTML attribute vs. DOM property
Attributes are defined by HTML. Properties are defined by the DOM (Document Object Model).
A few HTML attributes have 1:1 mapping to properties.
id
is one example.Some HTML attributes don't have corresponding properties.
colspan
is one example.Some DOM properties don't have corresponding attributes.
textContent
is one example.Many HTML attributes appear to map to properties ... but not in the way you might think!
That last category is confusing until you grasp this general rule:
Attributes initializeDOM properties and then they are done. Property values can change; attribute values can't.
For example, when the browser renders
<input type="text" value="Bob">
, it creates a corresponding DOM node with avalue
property initialized to "Bob".When the user enters "Sally" into the input box, the DOM element
value
propertybecomes "Sally". But the HTMLvalue
attributeremains unchanged as you discover if you ask the input element about that attribute:input.getAttribute('value')
returns "Bob".The HTML attribute
value
specifies the initialvalue; the DOMvalue
property is the currentvalue.The
disabled
attribute is another peculiar example. A button'sdisabled
property isfalse
by default so the button is enabled. When you add thedisabled
attribute, its presence alone initializes the button'sdisabled
property totrue
so the button is disabled.Adding and removing the
disabled
attribute disables and enables the button. The value of the attribute is irrelevant, which is why you cannot enable a button by writing<button disabled="false">Still Disabled</button>.
Setting the button's
disabled
propertydisables or enables the button. The value of the propertymatters.The HTML attribute and the DOM property are not the same thing, even when they have the same name.
HTML 属性与 DOM 属性
属性由 HTML 定义。属性由 DOM(文档对象模型)定义。
一些 HTML 属性与属性有 1:1 的映射关系。
id
就是一个例子。某些 HTML 属性没有相应的属性。
colspan
就是一个例子。一些 DOM 属性没有相应的属性。
textContent
就是一个例子。许多 HTML 属性似乎映射到属性……但不是您想象的方式!
在您掌握以下一般规则之前,最后一类令人困惑:
属性初始化DOM 属性,然后它们就完成了。属性值可以改变;属性值不能。
例如,当浏览器渲染时
<input type="text" value="Bob">
,它会创建一个相应的 DOM 节点,该节点的value
属性初始化为“Bob”。当用户在输入框中输入“Sally”时,DOM 元素
value
属性变为“Sally”。但是,当您向 input 元素询问该属性时,您会发现HTMLvalue
属性保持不变:input.getAttribute('value')
返回“Bob”。HTML 属性
value
指定初始值;DOMvalue
属性是当前值。该
disabled
属性是另一个特殊的例子。默认情况下,按钮的disabled
属性false
是启用的。当您添加disabled
属性时,它的存在将按钮的disabled
属性初始化为,true
因此按钮被禁用。添加和删除
disabled
属性禁用和启用按钮。属性的值是不相关的,这就是为什么你不能通过写来启用按钮<button disabled="false">Still Disabled</button>.
设置按钮的
disabled
属性会禁用或启用按钮。财产的价值很重要。HTML 属性和 DOM 属性不是一回事,即使它们具有相同的名称。
回答by sibidiba
The answers already explain how attributes and properties are handled differently, but I really would like to point out how totally insanethis is. Even if it is to some extent the spec.
答案已经解释了如何以不同的方式处理属性和属性,但我真的想指出这是多么疯狂。即使它在某种程度上是规范。
It is crazy, to have some of the attributes (e.g. id, class, foo, bar) to retain only one kind of value in the DOM, while some attributes (e.g. checked, selected) to retain two values; that is, the value "when it was loaded" and the value of the "dynamic state". (Isn't the DOM supposed to be to represent the state of the documentto its full extent?)
疯狂的是,让一些属性(例如id, class, foo, bar)在 DOM 中只保留一种值,而某些属性(例如checked、selected)保留两种值;即“加载时”的值和“动态状态”的值。(难道 DOM 不应该代表文档的全部状态吗?)
It is absolutely essential, that two input fields, e.g. a textand a checkboxbehave the very same way. If the text input field does not retain a separate "when it was loaded" value and the "current, dynamic" value, why does the checkbox? If the checkbox does have two values for the checkedattribute, why does it not have two for its classand idattributes? If you expect to change the value of a text*input* field, and you expect the DOM (i.e. the "serialized representation") to change, and reflect this change, why on earth would you not expect the same from an inputfield of type checkboxon the checked attribute?
绝对必要的是,两个输入字段(例如文本和复选框)的行为方式完全相同。如果文本输入字段没有保留单独的“加载时”值和“当前、动态”值,为什么复选框会保留?如果复选框的checked属性有两个值,为什么它的class和id属性没有两个值?如果您希望更改文本*input* 字段的值,并且您希望 DOM(即“序列化表示”)发生更改并反映此更改,那么您到底为什么不期望输入字段的值相同?输入复选框在checked属性上?
The differentiation, of "it is a boolean attribute" just does not make any sense to me, or is, at least not a sufficient reason for this.
“它是一个布尔属性”的区别对我来说没有任何意义,或者至少不是充分的理由。
回答by Daniel Ruf
well these are specified by the w3c what is an attribute and what is a property http://www.w3.org/TR/SVGTiny12/attributeTable.html
好吧,这些是由 w3c 指定的,什么是属性,什么是属性 http://www.w3.org/TR/SVGTiny12/attributeTable.html
but currently attr and prop are not so different and there are almost the same
但目前 attr 和 prop 并没有那么不同,几乎相同
but they prefer prop for some things
但他们更喜欢某些事情的道具
Summary of Preferred Usage
The .prop() method should be used for boolean attributes/properties and for properties which do not exist in html (such as window.location). All other attributes (ones you can see in the html) can and should continue to be manipulated with the .attr() method.
首选用法摘要
.prop() 方法应该用于布尔属性/属性和 html 中不存在的属性(例如 window.location)。所有其他属性(您可以在 html 中看到的属性)可以并且应该继续使用 .attr() 方法进行操作。
well actually you dont have to change something if you use attr or prop or both, both work but i saw in my own application that prop worked where atrr didnt so i took in my 1.6 app prop =)
好吧,实际上,如果您使用 attr 或 prop 或两者都使用,则不必更改某些内容,两者都有效,但我在自己的应用程序中看到 prop 在 atrr 没有的情况下有效,因此我采用了我的 1.6 app prop =)
回答by Willem van der Veen
Difference HTML properties and attributes:
区别 HTML 属性和属性:
Let's first look at the definitions of these words before evaluating what the difference is in HTML:
在评估 HTML 中的区别之前,让我们先看看这些词的定义:
English definition:
英文定义:
- Attributes are referring to additional information of an object.
- Properties are describing the characteristics of an object.
- 属性是指对象的附加信息。
- 属性是描述对象的特征。
In HTML context:
在 HTML 上下文中:
When the browser parses the HTML, it creates a tree data structure wich basically is an in memory representation of the HTML. It the tree data structure contains nodes which are HTML elements and text. Attributes and properties relate to this is the following manner:
当浏览器解析 HTML 时,它会创建一个树数据结构,它基本上是 HTML 的内存表示。树数据结构包含节点,这些节点是 HTML 元素和文本。与此相关的属性和属性是以下方式:
- Attributesare additional information which we can put in the HTML to initializecertain DOM properties.
- Propertiesare formed when the browser parses the HTML and generates the DOM. Each of the elements in the DOM have their own set of properties which are all set by the browser. Some of these properties can have their initial value set by HTML attributes. Whenever a DOM property changes which has influence on the rendered page, the page will be immediately re rendered
- 属性是我们可以放入 HTML 以初始化某些 DOM属性的附加信息 。
- 属性是在浏览器解析 HTML 并生成 DOM 时形成的。DOM 中的每个元素都有自己的一组属性,这些属性都由浏览器设置。其中一些属性的初始值可以由 HTML 属性设置。每当影响渲染页面的 DOM 属性发生变化时,页面将立即重新渲染
It is also important to realize that the mapping of these properties is not 1 to 1. In other words, not every attribute which we give on an HTML element will have a similar named DOM property.
认识到这些属性的映射不是 1 到 1 的也很重要。换句话说,并不是我们在 HTML 元素上提供的每个属性都具有类似的命名 DOM 属性。
Furthermore have different DOM elements different properties. For example, an <input>
element has a value property which is not present on a <div>
property.
此外具有不同的 DOM 元素不同的属性。例如,一个<input>
元素具有一个属性上不存在的 value<div>
属性。
Example:
例子:
Let's take the following HTML document:
让我们以下面的 HTML 文档为例:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8"> <!-- charset is a attribute -->
<meta name="viewport" content="width=device-width"> <!-- name and content are attributes -->
<title>JS Bin</title>
</head>
<body>
<div id="foo" class="bar foobar">hi</div> <!-- id and class are attributes -->
</body>
</html>
Then we inspect the <div>
, in the JS console:
然后我们检查<div>
, 在 JS 控制台中:
console.dir(document.getElementById('foo'));
We see the following DOM properties (chrome devtools, not all properties shown):
我们看到以下 DOM 属性(chrome devtools,未显示所有属性):
- We can see that the attribute id in the HTML is now also a id property in the DOM. The id has been initialized by the HTML (although we could change it with javascript).
- We can see that the class attribute in the HTML has no corresponding class property (
class
is reserved keyword in JS). But actually 2 properties,classList
andclassName
.
- 我们可以看到 HTML 中的 id 属性现在也是 DOM 中的 id 属性。id 已由 HTML 初始化(尽管我们可以使用 javascript 更改它)。
- 我们可以看到 HTML 中的 class 属性没有对应的 class 属性(
class
在 JS 中是保留关键字)。但实际上 2 个属性,classList
和className
.