jquery中的attr、prop

在html中,如果想获取某个标签的某个属性值,可以使用attr()和prop()这两个方法,但是这两个方法还是有区别的,小编在这里记录一下。

attr():对于html我们自定义的DOM属性,一般使用该方法。自定义的像peoId(存个id值)、data(数据)之类的。

prop():对于html自带的属性,一般使用该方法。自带的像class、id、name、href、type等。

<html>
	<head>
<script src="http://libs.baidu.com/jquery/2.0.0/jquery.js"></script>
</head>
	<body>
		<input type="checkbox" id="c1" name="check" peoId="bb" checked>复选框1
		<input type="checkbox" id="c2" name="check" peoId="cc">复选框2
		<a href="https://baidu.com" data-target="a2" id="a1">百度一下,你就知道
	<script>
		var c1 = $("#c1")
		var c2 = $("#c2")
		var a1 = $("#a1")
		console.log(c1.prop("checked")+"--"+c1.attr("checked"))
		//true--checked	复选框如果选中的话,使用prop获取的是true,而attr获取的是checked的属性值
		console.log(c2.prop("checked")+"--"+c2.attr("checked"))
		//false--undefined	复选框如果未选中的话,使用prop获取的是false,而attr获取的是undefined,因为此时无checked属性
		console.log(a1.prop("href")+"--"+a1.attr("href"))
		//https://baidu.com/--https://baidu.com		如果获取的是html自带的属性值,则使用两个方法基本上都可以,但最好使用prop方法
		console.log(a1.prop("data-target")+"--"+a1.attr("data-target"))
		//undefined--a2		如果获取的是html自定义的属性,使用prop方法是获取不到值的,需使用attr方法
	</script>
	</body>
</html>

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值