jquery,checkbox无法用attr()二次勾选

今晨,漂亮的测试妹妹提了个奇怪的bug,说我一功能checkbox时隐时现,比如第一次打开有勾选,第n次打开可能就不选了。

 

想到与美女有亲密接触机会,马上鸡动起来。

经过偶层层抽次剥茧(da da jiang you),终于知道了原因:attr()在二次选中勾选框时,失效。

比如,如下HTML页面,一点【选中】、二点【取消选中】、三点【选中】,瞧,不行了呗。

复制代码
<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>prop demo</title>
  <style>
  img {
    padding: 10px;
  }
  div {
    color: red;
    font-size: 24px;
  }
  </style>
  <script src="https://code.jquery.com/jquery-1.10.2.js"></script>
</head>
<body>
 
  <input type="checkbox" checked="checked">
  <input type="checkbox">
  <input type="checkbox">
  <input type="checkbox" checked="checked">
 
<script>
$( "input[type='checkbox']" ).prop( "checked", function( i, val ) {
  return !val;
});
</script>
 
</body>
</html>
1.html
复制代码

 

解决方案,是使用prop()替换attr()方法(在Jquery1.6以上),如下代码:

复制代码
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Attr checked</title>
<script type="text/javascript" src="./js/jquery-1.11.2.js"></script>
<script type="text/javascript">
    function switchChecked(flag) {
        $("input[type='checkbox']").prop('checked', flag);
    }
</script>
</head>
<body>
    <input type="checkbox" />
    <input type="button" onclick="switchChecked(true)" value="选中">
    <input type="button" onclick="switchChecked(false)" value="取消选中">
</body>
</html>
2.html
复制代码

 

关于官方文档,见:http://api.jquery.com/attr/

或者http://api.jquery.com/prop/

摘抄如下:“As of jQuery 1.6, the .attr() method returns undefined for attributes that have not been set. To retrieve and change DOM properties such as the checked, selected, or disabled state of form elements, use the .prop() method.”

posted @   nick_huang  阅读(1552)  评论(0编辑  收藏  举报
编辑推荐:
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
阅读排行:
· Ollama——大语言模型本地部署的极速利器
· 使用C#创建一个MCP客户端
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· Windows编程----内核对象竟然如此简单?
· ollama系列1:轻松3步本地部署deepseek,普通电脑可用
点击右上角即可分享
微信分享提示