当满足条件时,用jQuery选中一个框

Check a box with jQuery when condition is met

本文关键字:一个 条件 满足 jQuery      更新时间:2023-09-26

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

取消

订阅复选框的自动取消选中工作正常。我无法开始工作的是,当未选中任何选择加入复选框时,自动选中取消订阅复选框。

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() 来设置检查状态

$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);
});

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');

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