jquery中.prop()和.attr()的区别 什么叫布尔型属性 property vs attributes , boolean attributes...

jquery 1.6之后出了个新方法 .prop() ,之后又改回去了点儿东西。那么现在 .prop() 与 .attr() 到底各自对应什么呢? 什么时候该用哪个?

一般的回答是,使用.prop()来获取property,使用.attr()来获取attributes。但这又引发了另一个问题,什么是property, 什么是attributes。

结束这种转圈圈的游戏吧。当我们在写一个html/xml的 mark up 时,比如

<input type='checkbox' value='male' name='gender' checked> male

此时attributes取到的就是解析这个html得到的属性,即:

这里写图片描述

attr(‘checked’)会得到checked 是因为这是一个boolean attribute ,也就是说,这种属性只要在html标签中出现了,就会有这个属性,attribute就会把它解析成 xx=’xx’ , 而prop中会认为是true。

写的时候要注意,要么只写xx, 要么写 xx=’xx’ 同名字符串,要不就是空字符串。

<div hidden='true'> </div>// this is wrong
<div hidden> </div>//ok
<div hidden=''></div>//ok
<div hidden='hidden'></div> //ok

from HTML5 Spec

2.5.2 Boolean attributes
A number of attributes are boolean attributes. The presence of a boolean attribute on an element represents the true value, and the absence of the attribute represents the false value.

If the attribute is present, its value must either be the empty string or a value that is an ASCII case-insensitive match for the attribute’s canonical name, with no leading or trailing whitespace.

The values “true” and “false” are not allowed on boolean attributes. To represent a false value, the attribute has to be omitted altogether.

the full list of boolean attributes in html 4.01 /xhtml1.0
所有这种布尔属性,现在还在用的主要有checked selected disabled readonly multiple ismap defer noresize

checked (input type=checkbox/radio)
selected (option)
disabled (input, textarea, button, select, option, optgroup)
readonly (input type=text/password, textarea)
multiple (select)
ismap isMap (img, input type=image)

defer (script)
declare (object; never used)
noresize noResize (frame)
nowrap noWrap (td, th; deprecated)
noshade noShade (hr; deprecated)
compact (ul, ol, dl, menu, dir; deprecated)

接下来继续说property 与 attribute

attribute 就是 解析 markup 中得到的属性,而 property是对于dom节点而言的 。是固有的,如果什么值都不给,也会有,不过是default值,而不是undefined
仍以input为例,标签中去掉checked之后,就会是

这里写图片描述

这其实就是attribute与property的区别了。attribute是解析markup(html标签)得到的,而property是固有的。
比如chrome浏览器中,一个dom元素打出.来,会给出这些提示的属性和方法。

这里写图片描述



这里插一笔 id 和class
id很少在用的时候改变。建议是,除非你清楚地知道你在做什么,不然不要动它。
class比较特殊,经常用它来变换css属性,注意在prop中没有class,只有className 和 classList
这里写图片描述

总结一下:
className 是字符串 以空格间隔 不好操作
classList 是数组 或者说是对象更合适 可以用[index]来取得class的每一个值 有个属性叫value就等于className 还有两个方法 add 与 remove,可以增删class。


关于怎么使用.prop() 和 .attr()

固有属性用prop DOM的会变化的属性,比如勾选了/不勾选,也用prop.

自己加的属性用.attr(),比如data-XX, 不然取不到。

以及,gulp压缩html的工具gulp-html-minifier中有个option,就是是否省略布尔型属性的,那个的含义就是在压缩后只显示其属性名,而不是readonly=”readonly”这样的

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值