何时访问属性(vs属性)? [英] When to access the attribute (vs the property)?

查看:79
本文介绍了何时访问属性(vs属性)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我从这篇文章收集,几乎总是想要成为访问DOM属性,而不是HTML属性。



那么罕见的有用异常是什么?在什么情况下访问HTML属性比访问DOM属性更好?

解决方案

有时,属性不会映射到更改



一个例子是复选框的选中的属性/属性。



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

 < input type =checkboxchecked =checked>改变我






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

alert('attribute:'+ this.getAttribute('checked')+'\\\
'+
'属性:'+ this.checked);
};






...而ID属性/属性会保持同步:

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

 < input type =复选框checked =checkedid =the_checkbox>改变我






  var i = 0; 

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

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

自定义属性通常根本不映射。在这些情况下,您需要获取该属性。






也许一个潜在更有用的情况是文本输入。

 < input type =textvalue =original> 

...其中属性不会随着来自DOM或用户的更改而改变。 p>




正如 @马特麦克唐纳,有DOM属性,会给你的初始值,将反映原来的属性值。

  HTMLInputElement.defaultChecked 
HTMLInputElement.defaultValue


I gather from this post that almost always one wants to be accessing the DOM property, not the HTML attribute.

So what are the rare useful exceptions? In what situation is accessing the HTML attribute better than accessing the DOM property?

解决方案

Sometimes the attribute doesn't map to changes in the property.

One example is the checked attribute/property of a checkbox.

DEMO: 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:

DEMO: 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.


As noted by @Matt McDonald, there are DOM properties that will give you the initial value that would reflect the original attribute value.

HTMLInputElement.defaultChecked
HTMLInputElement.defaultValue

这篇关于何时访问属性(vs属性)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆