簡體   English   中英

jQuery邏輯問題。 如果選中了其他復選框,則需要取消選中它,反之亦然

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

我有下面的代碼

如果選中了一個復選框,則應取消選中另一個復選框,然后顯示一個div。 如果選中了另一個復選框,則應取消選中另一個復選框並顯示d​​iv。

它以一種方式工作,但不是另一種方式。 我無法弄清楚如何使其雙向工作。

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

另外(也沒有那么有吸引力),您還可以測試clicked元素的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();
        }
    })
})

給兩個相同的類名,並在要顯示的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/

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM