【问题标题】:Check a box with jQuery when condition is met满足条件时用 jQuery 选中一个框
【发布时间】:2013-11-14 18:48:12
【问题描述】:

我有五个选择加入复选框和一个取消订阅复选框。当我单击选择加入复选框时,如果没有选择加入复选框保持选中状态,则应该自动选中取消订阅复选框。如果我随后选中其中一个选择加入框,则取消订阅复选框应该被自动取消选中。

取消订阅复选框的自动取消选中效果很好。当没有选中任何选择加入复选框时,我无法开始工作的是自动检查取消订阅复选框。

var $jQ = jQuery.noConflict();

$jQ("#Unsubscribed").click(function(event) {
    opt_ins_unchecked = $(":checkbox" ).not('#Unsubscribed').not(':checked').length;
    if (opt_ins_unchecked == 5 && !$jQ("#Unsubscribed").is(':checked')){
        event.preventDefault();

    } else {
            $jQ("input[name=Opt-In_Premium_Content],input[name=Opt-In_Product_Updates],input[name=Opt-In_Industry_Best_Practices],input[name=Opt-In_Events_Webinars],input[name=Opt-In_Education_Training]").attr("checked", false);
    }
});

$jQ("#Opt-In_Premium_Content, #Opt-In_Product_Updates, #Opt-In_Industry_Best_Practices, #Opt-In_Events_Webinars, #Opt-In_Education_Training").click(function() {
    opt_ins_unchecked = $(":checkbox" ).not('#Unsubscribed').not(':checked').length;
    if (opt_ins_unchecked == 5){
        $jQ("#Unsubscribed").attr("checked", true);
    }

    if (opt_ins_unchecked != 0){
        $jQ("#Unsubscribed").attr("checked", false);
    }
});

当我没有选中任何选择加入复选框时,为什么不运行 $jQ("#Unsubscribed").attr("checked", true); 行?当我取消选中所有选择加入复选框时,如何使取消订阅框被选中?

【问题讨论】:

  • 最好使用.prop()而不是.attr()
  • @DrixsonOseña 我使用的是 jQuery 1.2.4,所以这不是一个选项。
  • 那是旧的,您至少应该使用 1.6+。即便如此,下面的答案也会更新
  • 大声笑,我无法控制。

标签: javascript jquery html checkbox conditional-statements


【解决方案1】:

事实证明它不起作用,因为两个 if 语句的计算结果都是 true

【讨论】:

    【解决方案2】:

    使用.prop()而不是.attr()设置检查状态

    $jQ("#Unsubscribed").prop("checked", true);
    

    试试

    var $unsubscribed = $jQ("#Unsubscribed");
    var $checks = $jQ("#Opt-In_Premium_Content, #Opt-In_Product_Updates, #Opt-In_Industry_Best_Practices, #Opt-In_Events_Webinars, #Opt-In_Education_Training");
    
    $checks.change(function () {
        $unsubscribed.prop("checked", $checks.filter(':checked').length == 0);
    });
    

    【讨论】:

      【解决方案3】:

      jQuery 1.6+ 推荐 prop() 而不是 attr():

      使用新的.prop() 函数:

      $jQ('#Unsubscribed').prop('checked', true);
      $jQ('#Unsubscribed').prop('checked', false);
      

      jQuery 1.5 及以下您可以使用attr,因为 prop() 不可用。

      或者你可以使用任何 jQuery:

      $jQ("#Unsubscribed").removeAttr('checked');
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2012-11-11
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多