美文网首页
property与attribute的区别

property与attribute的区别

作者: 袁韩 | 来源:发表于2016-06-05 09:38 被阅读1409次

同样是获得element的style属性,有两种方式el.styleel.getAttribute('style')。前者我们叫styleelproperty,后者我们叫styleelattribute

参考attibute vs propertystack overflow上关于$.prop与$.attr的回答,我们可以总结为以下:

  1. DOM element是一个object,它具有的属性叫做property,property的类型有很多种,可以是string,number,obejct,function。
    但是getAttribute(attrName)的返回值始终是string类型。
  2. DOM element通过getAttribute方法得到某属性的值,这个值的起源是html文本上的定义值。
    对于简书的编辑栏,html文本是这样定义的
<textarea class="text mousetrap" name="note_content" style="height: 573px;">
</textarea>

浏览器根据这个文本生成dom element,发现这个定义里包含三个属性,分别是class,name,style。我们在chrome dev tool里面查看这三个属性:

$0.getAttribute('class') // "text mousetrap"
$0.getAttribute('name') // "note_content"
$0.getAttribute('style') // "height: 573px;"

而直接通过el.propName或者el[propName],我们得到的是el作为dom element的属性,大部分prop与attr名称相同,但是有些不同,比如class与className

$0.className // "text mousetrap"
$0.classList // ['text', 'mousetrap'] ps: classList不是array类型
$0.name // "note_content"
$0.style 
/* **
CSSStyleDeclaration {
  0: "height", 
  alignContent: "", 
  alignItems: "", 
  alignSelf: "",
  ...
}
** */

查看style的值,我们可以发现其中的差别。

  1. 在实际应用中,大部分时候我们只需关注property,比如class,id,name,checked等等。它们通常代表有意义的web api。我们都知道class的语义,不管这个意义怎么表示。再看前面的element,它具有两个类名textmousetrap,那么无论是通过el.className = 'text mousetrap foo',或者el.classList.add('foo'),还是el.setAttribute('class', 'text mousetrap foo'),最终我们都成功地添加了新类名foo,并且这种结果与el.classNameel.getAttribute('class')是一致的。
  2. 当我们需要一些自定义的属性时,那么我们应该用attribute。最常见的就是定义在html文本里的data-*属性。

最后查看sprint.js对于prop与attr的实现,我们可以加深对prop与attr区别的理解。

相关文章

  • property与attribute的区别

    同样是获得element的style属性,有两种方式el.style和el.getAttribute('style...

  • JavaScript 常见面试题分析(三)

    01 property 和 attribute 的区别 property 修改对象属性,不会体现到 HTML 结构...

  • property和attribute

    property和attribute 两种有何区别? property指的是 dom 本身内置的属性,比如tagN...

  • property&attribute

    2017年4月6日DOM 中 Property 和 Attribute 的区别转载:博客园property 和 a...

  • C#特性 1

    什么是Attribute?Attribute是干什么使的?Attribute与Property到底有什么区...

  • C#面试题和答案

    1、C#中 property 与 attribute的区别,他们各有什么用处,这种机制的好处在哪里? proper...

  • web小结

    DOM操作部分 DOM的数据结构是一种树 attribute和property的区别 节点的property 节点...

  • Attribute和Property的区别

    1. Attribute和Property的概念 attribute : 特性,XML 元素中的概念,用于描述 X...

  • property和attribute的区别

    property 和 attribute非常容易混淆,两个单词的中文翻译也都非常相近(property:属性,at...

  • attribute和property的区别

    看到别的文章 要么格式乱 要么没读懂这篇文章个人感觉恰到好处 第一个问题: 什么是 attribute & 什么是...

网友评论

      本文标题:property与attribute的区别

      本文链接:https://www.haomeiwen.com/subject/wxqrdttx.html