JavaScript:propetry 与 attribute 的区别

来源:互联网 发布:淘宝美工练手 编辑:程序博客网 时间:2024/04/30 06:03

property和attribute翻译成中文都有属性,特性的意思,以至于在刚接触的时候,并没有真正把它们分开。现在做个梳理。

**

1.什么是property?

**
JS DOM对象拥有properties。这些properties有点像特殊元素的实例变量。比如,一个property可以是不同的类型(boolean,string,etc..)。
可以通过jQuery的prop方法获得property的值。

<a href='page2.html' class='link classes' name='linkName' id='linkID'>Hi</a>$('#linkID').prop('href'); // returns "http://example.com/page2.html"$('#linkID').prop('name'); // returns "linkName"$('#linkID').prop('id'); // returns "linkID"$('#linkID').prop('className'); // returns "link classes"

当然,也可以通过prop()修改property的值。

<a href='page2.html'>Hi</a>$('#linkID').prop('href', 'page1.html');$('#linkID').prop('href'); // returns "http://example.com/page1.html"

**

2.什么是attribute?

**
attribute是HTML 标签所拥有的,而不是存在于DOM中的。他们与property神似。一般来说,当可以用property的时候,就不要用attribute了。
attribute仅仅只有string这一种类型。

<input type="checkbox" checked=true/>$('input').prop('checked'); // returns true$('input').attr('checked'); // returns "checked"

如果一个元素有一个默认的值,即使这个值被修改后,attr()也只能返回默认的值。

<input type="text" name="username" value="user123">$('input').prop('value', '456user');$('input').prop('value'); // returns "456user"$('input').attr('value'); // returns "user123"

想自定义属性时, attribute就显得非常有用了,此时,与property就无关了。

<input type="text">$('input').attr('customAttribute', 'something custom');$('input').attr('customAttribute'); // returns "something custom"$('input').prop('customAttribute'); // returns undefined

查看demo
总而言之:property是JS DOM 对象拥有的,attribute是html标签拥有的。

0 0
原创粉丝点击