jQuery逻辑的问题.如果选中了另一个复选框,则需要取消选中一个复选框,反之亦然

Problem with jQuery logic. Need to uncheck one checkbox if other is checked, vice versa

本文关键字:复选框 取消 反之亦然 一个 如果 另一个 jQuery 问题      更新时间:2023-09-26

我有下面的代码

如果一个复选框被选中,它应该取消选中另一个复选框,然后显示一个div。如果另一个复选框被选中,它应该取消选中另一个复选框,并显示div。

它在一个方向上工作,而不是另一个方向。

我不知道怎样才能使两者兼顾。
    $('#ssUseDates, #isSearchByDate').click(function() {
    if($('#isSearchByDate').attr('checked')) {
        $('#ssUseDates').removeAttr('checked');
        $('#searchDates').show();
    }
    else if($('#ssUseDates').attr('checked')) {
        $('#isSearchByDate').removeAttr('checked');
        $('#searchDates').show();
    }

如果我选中#ssUseDates框,然后选中#isSearchByDate框,它工作得很好,取消选中#ssUseDates框,然后显示div。如果我选中#isSearchByDate框,那么#ssUseDates框,它不工作,不会让框选中,也不会取消选中其他

谢谢您的建议

我认为共享click()中的if...else...是您的问题。试着把它分开:http://jsfiddle.net/TG2ne/6/

$(function() {
    $('#isSearchByDate').click(function() {
        if ($('#isSearchByDate').attr('checked')) {
            $('#ssUseDates').removeAttr('checked');
            $('#searchDates').show();
        } 
    });
    $('#ssUseDates').click(function() {
        if ($('#ssUseDates').attr('checked')) {
            $('#isSearchByDate').removeAttr('checked');
            $('#searchDates').show();
        }
    });
});

或者(不太吸引人的),你也可以测试被点击元素的id:http://jsfiddle.net/TG2ne/11/

$(function() {
    $('#ssUseDates, #isSearchByDate').click(function() {
        if ($(this).attr("id") == "isSearchByDate" && $('#isSearchByDate').attr('checked')) {
            $('#ssUseDates').removeAttr('checked');
            $('#searchDates').show();
        } else if ($(this).attr("id") == "ssUseDates" && $('#ssUseDates').attr('checked')) {
            $('#isSearchByDate').removeAttr('checked');
            $('#searchDates').show();
        }
    })
})

给两个相同的类名,并添加一个ref到你想显示的id,试试这个:

$('.checkClass').change(function() {
    if($(this).is(':checked')) {
        $('.checkClass').not(this).attr('checked', false).change();
        $('#'+$(this).attr('ref')).show();
    }
    else {
        $('#'+$(this).attr('ref')).hide();
    }
});

这里有一个小提琴:http://jsfiddle.net/maniator/9dvDd/5/