prop和attr

1. 往checkbox添加checked属性

	<input type="checkbox" name="test" value="" checked="checked"/>
	<input type="checkbox" name="test" value="" checked=""/>
	<input type="checkbox" name="test" value="" checked="maomao"/>
	<input type="checkbox" name="test" value=""/>

上面前三种出来的结果相同,都可勾选,证明只要添加checked属性,不管值为何,都可,系统会自动赋值


2. prop和attr

<form action="" method="post">
	<input type="checkbox" name="test1" value=""/>
	<input type="checkbox" name="test2" value=""/>
	<input type="checkbox" name="test3" value=""/>
	<input type="checkbox" name="test4" value=""/>
	<input type="submit" value="submit">
</form>
<script>
	$("input[name='test1']").prop("checked","checked");
	$("input[name='test2']").prop("checked","maomaojiong");
	$("input[name='test3']").prop("checked","");
	$("input[name='test4']").attr("checked","checked");
</script>




结果是



除了第三个没勾选,其他都勾选了,为什么会出现这种情况?在第一块代码片段是,checked=" "不是也勾选了吗?


因为prop是布尔值,只有true和false,你赋不为空即为true。

这里有个问题,attr()应该只有添加属性的作用,并没有使checked=“checked”动作生效,不知道为什么也勾选了;而prop()则可以使其生效。



3. 在高版本的iquery引入prop后,什么时候该用prop,什么时候该用atrr呢?

 主流的观点的处理固有属性时用prop(); 处理自定义属性时用attr();

举个例子:

<a href="https://www.aliyun.com/" target="_blank" id="yun">阿里云</a>

上面a标签里面的属性都是w3c标准里带有的固有属性

<span class="_blank" action="del">删除</span>

在这个标签有一个我们自定义的action



下面让我们操作下(dom结构接上面)

document.write("<pre>");
document.writeln($("a").prop("id"));
document.writeln($("a").attr("id"));
document.writeln("---------分割线---------");
document.writeln($("span").prop("action"));
document.writeln($("span").attr("action"));
document.write("</pre>");


结果出来是:


在用prop输出span的自定义属性action时,浏览器返回了underfined。

因次prop只能拿来获取标签的固有属性;而attr都可。



再来看一个例子:

html
<input id="ck" type="checkbox"/>是否可见
<input id="ck2" type="checkbox" checked="checked" />是否可见
js
console.log($("#ck").prop("checked"));
console.log($("#ck2").prop("checked"));	
console.log($("#ck").attr("checked"));
console.log($("#ck2").attr("checked"));

返回结果:


三个例子很明显那了,prop()用于固有属性;特别的有checked这种,返回布尔值;

attr()返回的是存在的属性的值,不存在则返回undeifined



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值