Attribute和自定义Property
DOM节点可能会有attribute和property. 有时候人们会分不清,因为他们是有关联的,但它们又是完全不同的。
property
DOM是一个对象。因此它可以像普通对象一样存储自定义property及方法。
下例将会给 document.body 添加自定义对象 myData。
document.body.myData = {
name: 'John'
}
alert(document.body.myData.name) // John
document.body.sayHi = function() {
alert(this.nodeName)
}
document.body.sayHi() // BODY
JavaScript中的自定义property和方法将不会影响到HTML。
自定义property也可以使用 for..in 进行遍历。
document.body.custom = 5
var list = []
for(var key in document.body) {
list.push(key)
}
alert(list.join('\n'))
自定义DOM property:
- 可以拥有任何值。property名称有大小写之分。
- 不会影响到HTML。
attribute
DOM节点使用下列方法来访问HTML attribute。
elem.hasAttribute(name)- 检查该attribute是否存在elem.getAttribute(name)- 获取attribute的值elem.setAttribute(name, value)- 设定attribute的值elem.removeAttribute(name)- 移除某个attribute
在IE<8和IE兼容视图中,attribute有些不一致
- 只有getAttribute 和 setAttribute 存在。
- 他们实际上修改DOM property,而不是attribtue。
- 当IE<8时 attribute和property 合并成了一个。有时候它会导致奇怪的结果,但是在这里讨论的设置方式没有任何问题。
与property想法,attribute有以下特性:
- 只能为字符串
- 名字与大小写无关,因为HTML attribute是大小写无关的。
- 当调用innerHTML时会显示出来。
- 你可以通过调用 attributes 属性对它们进行遍历。
例如,让我们看看以下的例子:
<body>
<div about="Elephant" class="smiling"></div>
<script>
var div = document.body.children[0]
alert( div.getAttribute('ABOUT') ) // (1)
div.setAttribute('Test', 123) // (2)
alert( document.body.innerHTML ) // (3)
</script>
</body>
当你运行上面的代码时,将会注意到:
- getAttribute('ABOUT') 会使用大写字母,但没有关系。
- 当你指定一个字符串或其他的原始数据类型时,将会自动转换为string。对象将会自动转换,但IE在这里有些问题,所以避免这么使用。
- innerHTML 会包含新的 "test" attribute
property和attribute的同步
所有的DOM节点都有标准属性。
例如,让我们看看 'A' 标签:详细请查看
它有 "href" 和 "accessKey" 和其他的一些attribute。除此之外,它还会从 HTMLElement 继承 "id" 和其他的一些 attribute。
标准的DOM属性将会和attribute进行同步。
id
例如,浏览器将会同步 "id" attribute 和 "id" property。
<script>
document.body.setAttribute('id','la-la-la')
alert(document.body.id) // la-la-la
</script>
href
无法保证相同的值。让我们举例说明 "href"
<a href="#"></a>
<script>
var a = document.body.children[0]
a.href = '/'
alert( 'attribute:' + a.getAttribute('href') ) // '/'
alert( 'property:' + a.href ) // IE: '/', others: full URL
</script>
那是因为,根据W3C规格,它必须为完整格式的链接。
还有一些attribute,它们会同步,但没有进行复制。例如 input.checked:
<input type="checkbox" checked>
<script>
var input = document.body.children[0]
alert( input.checked ) // true
alert( input.getAttribute('checked') ) // empty string
</script>
input.checked 的property 要么true,或者false。但在attribute中它是所设置的字符串。
value
有些内置的属性只会单向同步。
例如,input.value 将被attribute同步:
<body>
<input type="text" value="markup">
<script>
var input = document.body.children[0]
input.setAttribute('value', 'new')
alert( input.value ) // 'new', input.value changed
</script>
</body>
但attribute不会被 property 同步
<body>
<input type="text" value="markup">
<script>
var input = document.body.children[0]
input.value = 'new'
alert(input.getAttribute('value')) // 'markup', not changed!
</script>
</body>
当"value"属性更新后 attribute 还会保留原来的值,原来的值可以用来检测input是否被改变,或对它进行重置。
class/className
"class" attribute 对应 "className" property。
因为 "class"在JavaScript中是一个保留单词,"class" attribute对应的属性为className。
<body>
<script>
document.body.setAttribute('class', 'big red bloom')
alert( document.body.className ) // ^^^
</script>
</body>
注意,上面的例子在IE<9时不正确,因为attribute和property混合在了一起。
我们可以很好地解决它,只需要当操作类的时候始终使用className而不是attribute。
- 将div赋值给一个变量
- 获取
"data-widgetName"attribute的值<body> <!-- hello world! don't remove me.--> <div data-widgetName="menu">Select the genre</div> <script>/* ... */</script> </body>
旧IE的趣事
首先当IE<9时所有的attribute和property会进行同步。
document.body.setAttribute('try-in-ie', 123)
alert( document.body['try-in-ie'] === 123 ) // true in IE
注意 类型也是一样的。当attribute没有变换为字符串。
其次,IE<8(或IE8兼容模式)property和attribute是一样的。这将会导致很多有趣的结果。
例如,property有大小写之分,但attribute不区分大小写。如果浏览器认为他们俩是一样的,下面的代码会导致什么结果呢?
document.body.abba = 1 // assign property (now can read it by getAttribute)
document.body.ABBA = 5 // assign property with another case
// must get a property named 'ABba' in case-insensitive way.
alert( document.body.getAttribute('ABba') ) // ??
浏览器会选择第一个值为默认值。它还会在getAttribute方法中提供仅限IE浏览器的第二个参数,它会辨别是否区分大小写。详细请看:MSDN getAttribute
除非IE<9 "class" attribute可以更改类。不要使用该attribute,要始终使用 className property。
为了与IE和睦相处,我们需要正确的使用attribute。
或,换句话说,尝试始终使用property,直到你确实需要使用attribute。
以下情况会让你真的需要attribute:
- 获取一个自定义HTML attribute,因为当使用DOM property时不会同步到HTML。
- 获取原始值,例如 INPUT value。
attribute作为DOM节点
attribute还可以通过 element.attributes 集合进行访问。
在attributes结合中,每个attribute 都有这些特性。它会有名字,值和其他的属性。
<span style="color:blue" id="my">text</span> <script> var span = document.body.children[0] alert( span.attributes['style'].value ) // "color:blue;" alert( span.attributes['id'].value ) // "my" </script>
顺便提一下,IE<8或IE兼容模式中 style attribute将会导致疯狂的结果。猜猜原因。
attribute DOM节点不是文档树的一部分,它们仅可以通过element元素进行访问。
总结
attribute和property都是DOM模型中的核心功能。
下面的表格表示关联点和不同点。
Property |
Attribute |
| 任意值 | 字符串 |
| 区分大小写 | 大小写无关 |
| 在innerHTML中不显示 | innerHTMl中显示 |
如果你想要在HTML中有自定义attribute,记住在HTML5中data-* attribute是有效地。查看HTML5标准中的自定义attribute
现实生活中,98%的DOM property将会被使用。
你应该只在下列两种情形中使用attribute。
- 获取一个自定义HTML attribute,因为当使用DOM property时不会同步到HTML。
- 获取原始值,例如 INPUT value。
Attribute和自定义Property的更多相关文章
- springboot(八)自定义Filter、自定义Property
自定义Filter 我们常常在项目中会使用filters用于录调用日志.排除有XSS威胁的字符.执行权限验证等等. Spring Boot自动添加了OrderedCharacterEncodingFi ...
- 代码走查25条疑问 C# 跳转新的标签页 C#线程处理 .Net 特性 attribute 学习 ----自定义特性 看懂 ,学会 .NET 事件的正确姿势-简单版
代码走查25条疑问 代码走查(Code Review) 是一个开发人员与架构师集中讨论代码的过程.通过代码走查可以提高代码的 质量,同时减少Bug出现的几率.但是在小公司中并没有代码走查的过程在这 ...
- HTML attribute 与 DOM property 的对比
HTML attribute vs. DOM property 要想理解 Angular 绑定如何工作,重点是搞清 HTML attribute 和 DOM property 之间的区别. attri ...
- DOM元素的Attribute(特性)和Property(属性) 【转载】
1.介绍: 上篇js便签笔记http://www.cnblogs.com/wangfupeng1988/p/3626300.html最后提到了dom元素的Attribute和Property,本文简单 ...
- 理解特性attribute 和 属性property的区别 及相关DOM操作总结
查一下英语单词解释,两个都可以表示属性.但attribute倾向于解释为特质,而property倾向于解释私有的.这个property的私有解释可以更方便我们下面的理解. 第一部分:区别点 第一点: ...
- 自定义Property属性动画
同步发表于 http://avenwu.net/customlayout/2015/04/06/custom_property_animation/ 代码获取 git clone https://gi ...
- Gradle学习系列之五——自定义Property
在本系列的上篇文章中,我们讲到了增量式构建,在本篇文章中,我们将讲到如何自定义Project的Property. 请通过以下方式下载本系列文章的Github示例代码: git clone https: ...
- .Net 特性 attribute 学习 ----自定义特性
什么是特性? [Obsolete("不要用无参构造函数",true)] 放在方式上, 该方法就不能使用了 [Serializable]放在类上面.该类就是可以序列化和反序列化使用 ...
- 利用描述符自定义property
class Lazyproperty: def __init__(self,func): #传的func函数是被描述的类中的函数属性 self.func = func def __get__(self ...
随机推荐
- MySQL(Percona Server) 5.6 主从复制
MySQL(Percona Server) 5.6.15 主库:192.168.2.21 从库:192.168.2.22 例如我们同步的数据库为:test. 如果需要同步多个数据库下面会有说明. My ...
- 7.echo(),print(),print_r()的区别
echo是PHP语句, print和print_r是函数,语句没有返回值,函数可以有返回值(即便没有用) print() 只能打印出简单类型变量的值(如int,string) print_r() ...
- SharePoint Configuration Wizard - Unable to upgrade SharePoint Products and Technologies because an upgrade is already in progress
故障描述 当要运行SharePonit Products and Technologies Configuration Wizard的时候,出现了如下图所示的错误提示. 错误信息为: Unable t ...
- 手动编译安装LNMP
yum -y install gcc gcc-c++ autoconf nss_ldap libjpeg libjpeg-devel libpng libpng-devel freetype free ...
- Rails--n+1查询
listings = Listing.includes(:property).where(id: ids)
- git 常见问题
RPC failed; error: RPC failed; curl 56 SSL read: error:00000000:lib(0):func(0):reason(0), er rno 100 ...
- 编译安装php5.5和php-fpm
1.下载指定源码包 2../configure --prefix=/usr/local/php53 --enable-fpm --enable-debug --with-gd --with-jpeg- ...
- Java基础语法
java基础学习总结——基础语法1 一.标识符
- How to inspect who is caller of func and who is the class of instance
1. Who is the class of self instance ? class aa(object): def a(self): if self.__class__.__name__ == ...
- opencv支持的机器学习算法
CXCORE库: Mahalanobis距离: K均值: CV库: 人脸检测/Haar分类器 ML库: 正态朴素贝叶斯分类器: 决策树: Boosting: 随机森林: EM算法: K近邻(KNN): ...