【问题标题】:How to remove checked="checked" for unchecked checkboxes with jQuery?如何使用 jQuery 删除未选中的复选框的选中 =“选中”?
【发布时间】:2013-08-07 19:21:08
【问题描述】:

这是我当前的脚本

 <script>
        $().ready(function(){

                $('.prettycheckbox').click(function () {
                      $('.prettycheckbox input').removeAttr('checked');
                      $('.prettycheckbox a').removeClass('checked'); 

                      $("a", this).addClass('checked');
                      $("input", this).addAttr("checked");
                });

        });
 </script>

但是效果不好,因为在链接中添加和删除类的部分效果很好,但是对于输入它不起作用。

如何使“选中”复选框看起来像这样:

<input class="payment_type" type="checkbox" value="1" name="payment_type" style="display: none;" checked="checked">

其他的都这样吗?:

<input class="payment_type" type="checkbox" value="1" name="payment_type" style="display: none;">

如何做到这一点?类似于使用 jquery 和复选框的输入单选类型?

【问题讨论】:

  • 方法是.attr( "checked", "checked" ),但这不是你想要的,因为属性"checked"引用.defaultChecked属性,你想改变.checked。更改.defaultChecked 属性或"checked" 属性只有在用户尚未触摸复选框时才会生效。
  • 由于某种原因,这是有效的;D $('.prettycheckbox input').removeAttr('checked'); $('.prettycheckbox a').removeClass('checked'); $("a", this).addClass('checked'); $("input", this).attr("checked", true);

标签: jquery


【解决方案1】:

在,

jQuery 1.6+

要更改复选框的属性,您应该使用.prop() 函数。

$('.prettycheckbox input').prop('checked', false);
$('.prettycheckbox input').prop('checked', true);

jQuery 1.5 及以下

.prop() 函数不存在,但.attr() 类似:

$('.prettycheckbox input').attr('checked', 'checked');

注意removeAttr 有效,但addAttr 无效。

【讨论】:

    【解决方案2】:

    使用prop() 更改checked 的值

    $('.prettycheckbox input').prop('checked', false);
    

    还有一点需要说明,方法addAttr不存在

    【讨论】:

    • 但这不取决于jquery版本,如果OP使用的是1.6之前的版本,他/她可能会使用.attr()
    • 这行得通:$('.prettycheckbox input').removeAttr('checked'); $('.prettycheckbox a').removeClass('checked'); $("a", this).addClass('checked'); $("input", this).attr("checked", true); 你能解释一下为什么吗?
    • @michaelkonstincs:尚不清楚您要做什么。您似乎正在尝试检查和取消选中相同的方法
    • @ClaudioRedi 我认为我在问题中提供的代码很清楚。我的意思是单击(),然后删除,删除,添加,添加。嗯,没关系。它可能只适用于高级 jquery 用户。
    • @michaelkonstincs:哈哈,是的,你的代码是我无法理解的杰作。
    【解决方案3】:

    试试这个

    document.getElementById("check1").checked = true;
    document.getElementById("check1").checked = false;
    

    【讨论】:

      猜你喜欢
      • 2014-12-31
      • 1970-01-01
      • 2019-09-18
      • 1970-01-01
      • 1970-01-01
      • 2013-01-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多