jQuery attr方法 第一次有效,第二次无效问题

本文介绍了一个常见问题的解决方案,即如何修正使用jQuery实现的全选功能在第二次点击时失效的问题。针对这一问题,文章提供了代码示例并说明了在jQuery 1.7及以上版本中应如何正确地操作checkbox的选择状态。

例如设置全选:

$(function(){
    //设置全选反选
        $("#all").click(function(){
        if(this.checked){ 
            $("input[name='id']").attr("checked",true);
        }else{   
            $("input[name='id']").attr("checked",false);
        }    
    }); 
}); 

点击all按钮 第一次全选有用第二次全选无效。因为jquery1.7以上的版本用此方法只能第一次好用,第二次就会失效,需要把 (":checkbox").attr("checked","checked");(“:checkbox”).prop(‘checked’,false); $(“:checkbox”).prop(‘checked’,true)

这是因为在重新排列每一列位置的过程中,我们只是简单地使用jQuery的insertAfter方法来移动每一列,但没有更新每一列的索引信息。因此,在第二次拖动时,索引信息已经失效,导致拖动无效。 为了解决这个问题,我们需要在重新排列每一列位置的同时,更新每一列的索引信息。我们可以使用jQuery的each方法来遍历每一列,并更新它们的索引信息。 以下是修改后的代码,可支持多次拖动: ```html <!DOCTYPE html> <html> <head> <title>Table with colspan and draggable columns</title> <style type="text/css"> table { border-collapse: collapse; } th, td { padding: 10px; border: 1px solid black; } th { background-color: #EEE; cursor: move; user-select: none; } td[colspan="2"] { text-align: center; background-color: #DDD; } </style> <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script> <script src="https://code.jquery.com/ui/1.12.1/jquery-ui.min.js"></script> <script type="text/javascript"> $(document).ready(function() { $("th").draggable({ axis: "x", opacity: 0.7, helper: "clone", start: function(event, ui) { $(ui.helper).css("background-color", "#EEE"); }, stop: function(event, ui) { var index = $(this).index(); var newIndex = $(ui.helper).index(); if (newIndex > index) { newIndex -= $(ui.helper).attr("colspan") - 1; } $(this).closest("table").find("tr").each(function() { $(this).children("th:eq(" + index + ")").insertAfter($(this).children("th:eq(" + newIndex + ")")); $(this).children("td:eq(" + index + ")").insertAfter($(this).children("td:eq(" + newIndex + ")")); $(this).children("th").each(function(i) { $(this).attr("data-index", i); }); $(this).children("td").each(function(i) { $(this).attr("data-index", i); }); }); } }); }); </script> </head> <body> <table> <thead> <tr> <th colspan="2">Header 1</th> <th>Header 2</th> <th>Header 3</th> <th>Header 4</th> </tr> </thead> <tbody> <tr> <td colspan="2">Content 1</td> <td>Content 2</td> <td>Content 3</td> <td>Content 4</td> </tr> <tr> <td colspan="2">Content 5</td> <td>Content 6</td> <td>Content 7</td> <td>Content 8</td> </tr> <tr> <td colspan="2">Content 9</td> <td>Content 10</td> <td>Content 11</td> <td>Content 12</td> </tr> </tbody> </table> </body> </html> ``` 在修改后的代码中,我们在重新排列每一列位置的同时,使用each方法来遍历每一列,并更新它们的索引信息。具体来说,我们为每一列添加了一个data-index属性,表示它的索引位置。这样,就可以支持多次拖动了。
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值