Jquery中prop方法获取属性的值

Jquery中prop方法获取属性的使用

今天在写django前端页面的时候遇到了逻辑上的问题,通过百度get到了这个知识点,前来分享

先来参考官方详解:

定义和用法
prop() 方法设置或返回被选元素的属性和值。

当该方法用于返回属性值时,则返回第一个匹配元素的值。

当该方法用于设置属性值时,则为匹配元素集合设置一个或多个属性/值对。

语法
返回属性的值:

$(selector).prop(property)
设置属性和值:

$(selector).prop(property,value)
使用函数设置属性和值:

$(selector).prop(property,function(index,currentvalue))
设置多个属性和值:

$(selector).prop({property:value, property:value,…})

可见,prop方法还是很强大的。这里我针对我的问题,主要介绍一下prop方法获取值处有坑地方,给大家举个例子。

这里,我放上了一个前端页面:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script src="jquery-3.4.1.min.js"></script>

    <link rel="stylesheet" href="bootstrap-3.3.7-dist/css/bootstrap.css">
    <link rel="stylesheet" href="bootstrap-3.3.7-dist/css/bootstrap.min.css">
    <script src="bootstrap-3.3.7-dist/js/bootstrap.min.js"></script>


</head>
<body>

 <input type="radio" name="ctype" id="fc1" value="1" class="with-gap" checked >
 <input type="radio" name="ctype" id="fc2" value="1" class="with-gap" >
 <input type="radio" name="ctype" id="f3" value="1" class="with-gap" >
 
<script>
 	a = $('input[name="ctype"]').prop("checked")
    console.log(a)
</script>
</body>
</html>

通过,在浏览器的控制台中的打印结果为true.

第二次,我改变了前端页面:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script src="jquery-3.4.1.min.js"></script>

    <link rel="stylesheet" href="bootstrap-3.3.7-dist/css/bootstrap.css">
    <link rel="stylesheet" href="bootstrap-3.3.7-dist/css/bootstrap.min.css">
    <script src="bootstrap-3.3.7-dist/js/bootstrap.min.js"></script>


</head>
<body>

 <input type="radio" name="ctype" id="fc1" value="1" class="with-gap"  >
 <input type="radio" name="ctype" id="fc2" value="1" class="with-gap" checked >
 <input type="radio" name="ctype" id="f3" value="1" class="with-gap" >
 
<script>
 	a = $('input[name="ctype"]').prop("checked")
    console.log(a)
</script>
</body>
</html>

我默认选中了第二个选框,
在浏览器中的打印居然变成了false,为什么呢?

通过仔细看官方文档,我才发现,官方文档说,当该方法用于返回属性值时,则返回第一个匹配元素的值。,注意,这里说的是匹配元素的值,而不是匹配成功的元素,所以就造成了上面的情况。果然,细心很重要呀。

希望能帮助到您,共勉。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值