jQuery在我的函数中帮助我检测复选框点击的逻辑

时间:2010-11-21 00:46:20

标签: jquery

我做了这个功能,需要一些帮助来整理逻辑流程。它在某种程度上起作用,只需要帮助清除错误。

我的HTML:

<span style="float: left;"><input type="checkbox" id="top" name="position" value="top" />&nbsp;Top&nbsp;&nbsp;</span>
<span style="float: left;"><input type="checkbox" id="bottom" name="position" value="bottom" />&nbsp;Bottom&nbsp;&nbsp;</span>
<span style="float: left;"><input type="checkbox" id="left" name="position" value="left" />&nbsp;Left&nbsp;&nbsp;</span>
<span style="float: left;"><input type="checkbox" id="center" name="position" value="center" />&nbsp;Center&nbsp;&nbsp;</span>
<span style="float: left;"><input type="checkbox" id="right" name="position" value="right" />&nbsp;Right</span>

这是我的jQuery函数:

/// Bind Position value to 'CSS : BackgroundPosition' ///       
var $positions;

function bgpos(){
    var pos = $positions.map(function() {
        if($('#top').attr('checked') == true)
            $('#bottom').attr('disabled', true);
        else
            $('#bottom').attr('disabled', false);

        if($('#bottom').attr('checked') == true)
            $('#top').attr('disabled', true);
        else
            $('#top').attr('disabled', false);

        if($('#left').attr('checked') == true){
            $('#right').attr('disabled', true);
            $('#center').attr('disabled', true);
        }else{
            $('#right').attr('disabled', false);
            $('#center').attr('disabled', false);
        }

        if($('#right').attr('checked') == true){
            $('#left').attr('disabled', true);
            $('#center').attr('disabled', true);
        }else{
        $('#left').attr('disabled', false);
        $('#center').attr('disabled', false);
        }

        if(this.checked) return this.id;
    }).get().join(' ');
    //$('#queue').html(pos);
    $('#topHeader').css({'backgroundPosition' : pos});
}

$(function() {
    $positions = $("form#frm_look_and_feel input[name='position']").change(bgpos);
});

如果有人有兴趣,这是我的jsFiddle:

http://jsfiddle.net/s2xi/nWT5J/2/

我遇到的一个问题是当你点击'Top'时它不会禁用'Bottom'但是当我点击'Bottom'时它会禁用'Top'并且当我点击'Left'时会出现同样的问题,我的'中心'不会被禁用,但点击'右'会禁用'左'和'中',就像它应该一样。

1 个答案:

答案 0 :(得分:2)

我的顶部/底部没有问题,但其他问题是因为#center的状态总是#right状态确定,因为它周围有一个if / else ...不管#left只是设置它。

同样.map()运行每个元素,你不希望这里有这个逻辑,把它带到这样的外面:

function bgpos(){
    bottom.disabled = top.checked;
    top.disabled = bottom.checked;
    left.disabled = center.checked || right.checked;
    center.disabled = left.checked || right.checked;
    right.disabled = left.checked || center.checked;
    var pos = $positions.map(function() {
        if(this.checked) return this.id;
    }).get().join(' ');
    $('#topHeader').css({'backgroundPosition' : pos});
    $('#output').html(pos);
}

在这种情况下,这些变量直接是DOM元素,因为它对我来说看起来更干净(并且如果重要的话,速度要快得多)。 You can test it out here


作为替代方案,请考虑为每个组like this使用单选按钮。