当前位置: 移动技术网 > IT编程>开发语言>JavaScript > JS中的“特性”与“属性”attribute与property

JS中的“特性”与“属性”attribute与property

2018年03月30日  | 移动技术网IT编程  | 我要评论
DOM元素的attribute和property很容易混倄在一起,分不清楚。特别区分一下。 attribute是HTML标签上的"特性",它的值只能够是字符串

DOM元素的attribute和property很容易混倄在一起,分不清楚。特别区分一下。

attribute是HTML标签上的"特性",它的值只能够是字符串
property是DOM中的"属性",是JavaScript里的对象;

attribute节点都是在HTML代码中可见的,而property只是一个普通的名值对属性。

之所以attribute和property容易混倄在一起的原因是,很多attribute节点还有一个相对应的property属性,比如p元素的id和class既是attribute,也有对应的property,不管使用哪种方法都可以访问和修改。

但是对于自定义的attribute节点,或者自定义property,两者就没有关系了。

例如:

1、

hello

其中,gameid自定义属性,因此只能用getAttribute访问,无法用e.propName访问

console.log( elem.getAttribute('gameid') ); // 880

console.log(elem.gameid); //undefined

console.log( elem.removeAttribute('gameid') ); // undefined 删除

2、自定义property节点

elem.myColor = “red”; // 添加

console.log( elem.myColor ) // “red”

console.log(elem.getAttribute('myColor')); //null

delete elem.myColor // 删除

如您对本文有疑问或者有任何想说的,请 点击进行留言回复,万千网友为您解惑!

相关文章:

验证码:
移动技术网