简体   繁体   English

何时访问属性(vs属性)?

[英]When to access the attribute (vs the property)?

I gather from this post that almost always one wants to be accessing the DOM property, not the HTML attribute. 我从这篇文章中收集到, 几乎总是有人想要访问DOM属性,而不是HTML属性。

So what are the rare useful exceptions? 那么什么是罕见的有用例外? In what situation is accessing the HTML attribute better than accessing the DOM property? 在什么情况下访问HTML属性比访问DOM属性更好?

Sometimes the attribute doesn't map to changes in the property. 有时,属性不会映射到属性中的更改。

One example is the checked attribute/property of a checkbox. 一个例子是复选框的checked属性/属性。

DEMO: http://jsfiddle.net/mxzL2/ 演示: http //jsfiddle.net/mxzL2/

<input type="checkbox" checked="checked"> change me

document.getElementsByTagName('input')[0].onchange = function() {

    alert('attribute: ' + this.getAttribute('checked') + '\n' +
          'property: ' + this.checked);
};

...whereas an ID attribute/property will stay in sync: ...而ID属性/属性将保持同步:

DEMO: http://jsfiddle.net/mxzL2/1/ 演示: http //jsfiddle.net/mxzL2/1/

<input type="checkbox" checked="checked" id="the_checkbox"> change me

var i = 0;

document.getElementsByTagName('input')[0].onchange = function() {

    this.id += ++i;
    alert('attribute: ' + this.getAttribute('id') + '\n' +
          'property: ' + this.id);
};

And custom properties generally don't map at all. 自定义属性通常根本不映射。 In those cases, you'll need to get the attribute. 在这些情况下,您需要获取该属性。


Perhaps a potentially more useful case would be a text input. 也许一个可能更有用的案例是文本输入。

<input type="text" value="original">

...where the attribute doesn't change with changes from the DOM or the user. ...随着DOM或用户的更改,属性不会发生变化。


As noted by @Matt McDonald , there are DOM properties that will give you the initial value that would reflect the original attribute value. 正如@Matt麦克唐纳所指出的那样 ,DOM属性会为您提供反映原始属性值的初始值。

HTMLInputElement.defaultChecked
HTMLInputElement.defaultValue

A rare exception is the case of attributes of a <form> element that could clash with elements in the form. 一个罕见的例外是<form>元素的属性可能与<form>元素冲突。 For example, consider the following HTML: 例如,请考虑以下HTML:

<form id="theForm" method="post" action="save.php">
    <input name="action" value="edit">
</form>

The problem is that any input within a form creates a property corresponding to the input's name in the form element, overriding any existing value for that property. 问题是表单中的任何输入都会在表单元素中创建与输入name对应的属性,从而覆盖该属性的任何现有值。 So in this case, the action property of the form element is a reference to the <input> element with name action . 所以在这种情况下,form元素的action属性是对带有name action<input>元素的引用。 If that input did not exist, the action property would instead refer to the action attribute and contain the string "save.php". 如果该输入不存在,则action属性将引用action属性并包含字符串“save.php”。 Therefore for properties of form elements corresponding to attributes, such as action and method , it's safest to use getAttribute() . 因此,对于与属性相对应的表单元素的属性,例如actionmethod ,使用getAttribute()是最安全的。

var form = document.getElementById("theForm");

// Alerts HTMLInputElement in most browsers
alert( form.action );

// Alerts "save.php"
alert( form.getAttribute("action") );

// Alerts "post" because no input with name "method" exists
alert( form.method ); 

This is unfortunate; 这很不幸; it would have been better if this mapping did not exist, since the elements property of the form already contains all the form elements keyed by name . 如果这个映射不存在会更好,因为表单的elements属性已经包含了所有按name键入的表单元素。 I think we have Netscape to thank for this one. 我想我们有网景来感谢这个。

Live demo: http://jsfiddle.net/z6r2x/ 现场演示: http//jsfiddle.net/z6r2x/

Other occasions to use attributes: 其他使用属性的场合:

  • When accessing custom attributes, such as <div mymadeupattr="cheese"></div> 访问自定义属性时,例如<div mymadeupattr="cheese"></div>
  • When serializing the DOM and you want values from the original HTML for input attributes such as value and checked . 序列化DOM时,您希望原始HTML中的值用于输入属性(如valuechecked

I can only come up with 2 more situations where accessing/setting attribute would have benefits over property. 我只能提出另外两种情况,其中访问/设置属性对财产有好处。

Style attribute: 样式属性:

In a case where you are not allowed to use any framework, you can use style attribute to set multiple styles at once like so: 在不允许使用任何框架的情况下,您可以使用style属性一次设置多个样式,如下所示:

elem.setAttribute( "style", "width:100px;height:100px;" );

instead of doing this: 而不是这样做:

elem.style.width = "100px";
elem.style.height = "100px";

or this: 或这个:

var styles = {width: "100px", height: "100px"}, style;

for( style in styles ) {
elem.style[style] = styles[style];
}

Be aware that setting style attribute overwrites the previous one. 请注意,设置样式属性会覆盖前一个属性。 And its probably better to write a multiple style setter function anyway. 无论如何,编写多样式setter函数可能更好。

Href attribute: Href属性:

A href attribute will usually contain a value like "/products", however the property will contain the resolved url, as in: " http://www.domain.com/products " instead of what you really want: "/products". href属性通常包含类似“/ products”的值,但该属性将包含已解析的URL,如:“ http://www.domain.com/products ”而不是您真正想要的:“/ products” 。 So if you wanna do something dynamically with links, then reading the href attribute instead of property is better because it has the value you intended it to be. 因此,如果你想用链接动态地做一些事情,那么读取href属性而不是属性是更好的,因为它具有你想要的值。

Update 更新

I suddenly found 2 more uses and I am sure there are more like this. 我突然发现了2个用途,我相信还有更多这样的用途。

If you want to see if an element has custom tab index set, the easy way is to see if the element has the attribute. 如果要查看元素是否具有自定义选项卡索引集,则简单的方法是查看该元素是否具有该属性。 Since the default value for .tabIndex -property depends on element and cannot be easily used to see if the element has custom tabIndex. 由于.tabIndex -property的默认值取决于元素,因此无法轻易查看该元素是否具有自定义tabIndex。

Seeing if element has a custom .maxLength property. 查看元素是否具有自定义.maxLength属性。 This cannot be seen from property either: 从财产中也看不到:

document.createElement("input").maxLength
//524288

It is impossible to tell if the value 524288 was there intentionally without dealing with the attribute. 如果没有处理属性,就无法判断值524288是否存在故意。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM