jquery单选框

jquery单选框,第1张

<!DOCTYPE html>

<html lang="en">

<head>

<meta charset="UTF-8">

<meta name="viewport" content="width=device-width, initial-scale=1.0">

<meta http-equiv="X-UA-Compatible" content="ie=edge">

<title>Document</title>

<script src="https://cdn.bootcss.com/jquery/3.3.0/jquery.min.js"></script>

</head>

<body>

<p>

<label for="radio_a">A</label>

<input type="radio" name="edit" id="radio_a" value="">

<input type="text" disabled />

</p>

<p>

<label for="radio_b">B</label>

<input type="radio" name="edit" id="radio_b" value="">

<input type="text" disabled />

</p>

<script async defer>

$(document).ready(function() {

$('input[type="radio"]').change(function(e) {

var self = this

$('input[type="text"]').prop('disabled', true)

$(self).next().prop('disabled', false)

$(self).next().focus()

})

})

</script>

</body>

</html>

单选按钮的选中与取消选中,是元素自带的属性checked来实现的

一般情况下:

这个方法就可以满足实现将其第一个单选按钮选中。

但是如果这个是根据后台传到页面的值来实现的一个动态单选按钮选中。

下一次再赋值选中时可能会造成多个单选按钮都被选中。

页面就识别不出来应该将哪一个单选元素选中。

当然这时可以使用:

然后再将需要的单选元素选中。

但是可能会出现BUG,页面上虽然单选元素的属性是被checked了的(chrome F12查看)。

但是效果没有体现出来。

这是为什么呢?

其实很简单,一开始实现选中与取消选中的方式就错误了

正确的姿势是:

这是因为prop才是官方推荐的 *** 作元素的固有属性,比如input标签的id/class/type/style等等

而attr更多的是用来 *** 作元素的自定义属性


欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/tougao/11141077.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2023-05-13
下一篇 2023-05-13

发表评论

登录后才能评论

评论列表(0条)

保存