叼花硬汉 2009-01-08 22:20 采纳率: 0%
浏览 676
已采纳

用 jQuery 设置"checked"复选框?

I'd like to do something like this to tick a checkbox using jQuery:

$(".myCheckBox").checked(true);

or

$(".myCheckBox").selected(true);

Does such a thing exist?

转载于:https://stackoverflow.com/questions/426258/setting-checked-for-a-checkbox-with-jquery

  • 写回答

28条回答 默认 最新

  • 10.24 2009-01-08 22:25
    关注

    jQuery 1.6+

    Use the new .prop() method:

    $('.myCheckbox').prop('checked', true);
    $('.myCheckbox').prop('checked', false);
    

    jQuery 1.5.x and below

    The .prop() method is not available, so you need to use .attr().

    $('.myCheckbox').attr('checked', true);
    $('.myCheckbox').attr('checked', false);
    

    Note that this is the approach used by jQuery's unit tests prior to version 1.6 and is preferable to using

    $('.myCheckbox').removeAttr('checked');
    

    since the latter will, if the box was initially checked, change the behaviour of a call to .reset() on any form that contains it - a subtle but probably unwelcome behaviour change.

    For more context, some incomplete discussion of the changes to the handling of the checked attribute/property in the transition from 1.5.x to 1.6 can be found in the version 1.6 release notes and the Attributes vs. Properties section of the .prop() documentation.

    Any version of jQuery

    If you're working with just one element, you can always just modify the HTMLInputElement's .checked property:

    $('.myCheckbox')[0].checked = true;
    $('.myCheckbox')[0].checked = false;
    

    The benefit to using the .prop() and .attr() methods instead of this is that they will operate on all matched elements.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(27条)

报告相同问题?

悬赏问题

  • ¥15 HFSS 中的 H 场图与 MATLAB 中绘制的 B1 场 部分对应不上
  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?