radio 判断一个元素是否被选中

选中有一个elem元素,现在判断它是否被选中 ,之前我们使用的是 $(elem).atter("checked") 可是有时候不管用。后来使用这种方式就可以了

如果被选中则返回true,未被选中则返回false

<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>Index</title>
    <script src="~/Scripts/jquery-1.10.2.js"></script>
</head>
<body>
    <div>
        <input type="radio" name="fruit" value="苹果" />苹果
        <input type="radio" name="fruit" value="橘子" />橘子
        <input type="radio" name="fruit" value="香蕉" />香蕉
        <button οnclick="fun.CheckSelectItem()">提交</button>
    </div>
</body>
</html>
<script type="text/javascript">
    var fun = {
        CheckSelectItem: function () {
            $.each($("input[name=fruit]"), function (key, element) {
                //使用prop("checked")检查element这个元素是否被选中,如果被选中则返回true,未被选中则返回false
                if ($(element).prop("checked")) { // $(element)是将element这个元素转化为jquery元素
                    alert("您的选中项是:" + element.value);
                }
            })
        }
    }
</script>



 //$("input[ name = 'r1' ]:checked") 获取name属性为r1 且被选中的 input表单   

判断一个单选框是否选中来执行某一段函数,可以使用JavaScript来实现。可以先获取到对应的单选框DOM元素,然后监听其change事件,当单选框的选中状态发生变化时,执行一个函数来判断是否选中,如果选中则执行相应的代码。代码示例: ```html <label> <input type="radio" name="mode" value="mode1" checked> 模式1 </label> <label> <input type="radio" name="mode" value="mode2"> 模式2 </label> <label> <input type="radio" name="mode" value="mode3"> 模式3 </label> <label> <input type="radio" name="mode" value="mode4"> 模式4 </label> <script> // 获取单选框元素 const mode1 = document.querySelector('input[value="mode1"]'); const mode2 = document.querySelector('input[value="mode2"]'); const mode3 = document.querySelector('input[value="mode3"]'); const mode4 = document.querySelector('input[value="mode4"]'); // 监听change事件 mode1.addEventListener('change', function() { if (this.checked) { // 执行相应的代码 console.log('模式1被选中'); } }); mode2.addEventListener('change', function() { if (this.checked) { // 执行相应的代码 console.log('模式2被选中'); } }); mode3.addEventListener('change', function() { if (this.checked) { // 执行相应的代码 console.log('模式3被选中'); } }); mode4.addEventListener('change', function() { if (this.checked) { // 执行相应的代码 console.log('模式4被选中'); } }); </script> ``` 这个示例中,我们获取到了每个单选框的DOM元素,然后分别监听它们的change事件。当某个单选框被选中时,相应的函数会判断是否选中,如果是则执行相应的代码。可以根据需要替换掉console.log中的代码,实现相应的功能。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值