在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>