Attribute vs property

72 篇文章 0 订阅
61 篇文章 0 订阅

这两者太容易混淆了,简单来说,DOM对象拥有property属性,是一种特定的变量,property可以指定为任意的变量,如字符串,数字,对象等,jquery1.6以后的版本可以使用$.prop(key)方法获得properties,举个例子

<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方法也可以更新数据:

set
$('#linkID').prop('href', 'page1.html');

get
$('#linkID').prop('href'); // returns "http://example.com/page1.html"

html拥有attribute,attribute只有字符串值没有别的。所以建议使用property而不是使用attribute。

<input type="checkbox" checked=true/>

$('input').prop('checked'); // returns true
$('input').attr('checked'); // returns "checked"

当html元素有默认值时,即使是值发生了改变,attribute也只是保持默认的。

<input type="text" name="username" value="user123">

$('input').prop('value', '456user');
$('input').prop('value'); // returns "456user"
$('input').attr('value'); // returns "user123"

但是在用户自定义数据时attribute才发挥出它的作用,

<input type="text">

$('input').attr('customAttribute', 'something custom');
$('input').attr('customAttribute'); // returns "something custom"
$('input').prop('customAttribute'); // returns undefined

property也可以实现自定义属性,但是不推荐使用,不是一个好的实践。

<input type="text">

$('input').prop('customAttribute', 'something custom');
$('input').prop('customAttribute'); // returns "something custom"
$('input').attr('customAttribute'); // returns undefined

reference:http://stackoverflow.com/questions/5874652/prop-vs-attr/5884994#5884994
http://api.jquery.com/prop/

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值