2

我想制作元素列表,您只能选择一个选项并取消选择此选项并查看原始元素列表。我希望能够在不先取消选择当前选择的选项的情况下选择其他元素。我希望这一切都有意义。

HTML

<ul id="mylist">
    <li>Element 1</li>
    <li>Element 2</li>
    <li>Element 3</li>
    <li>Element 4</li>
    <li>Element 5</li>
    <li>Element 6</li>
</ul>

jQuery

$('#mylist').on('click', 'li', function () {
    $('#mylist li').removeClass('selected');
    $('#mylist li').addClass('not-selected');
    $(this).removeClass('not-selected');
    $(this).addClass('selected');
    $(this).click(function () {
        $('#mylist li').removeClass('selected');
        $('#mylist li').removeClass('not-selected');
    });
});

CSS

ul {
    list-style: none;
    margin: 0;
    padding: 0;
}

ul li {
    float: left;
    display inline-block;
    width: 100px;
    height: 100px;
    border: 1px solid black;
    margin: 0 10px 10px 0px;
}

ul li.selected {
    background-color: #f535d7;
}

ul li.not-selected {
    background-color: #bbb;
    opacity: .2;
}

这是我走了多远:http: //jsfiddle.net/vaidasb/rMRgF/5/

4

3 回答 3

2

将您的 javascript 更改为:

$('#mylist').on('click', 'li', function () {
    if ($(this).hasClass('selected'))
    {
        $(this).removeClass('selected');
        $('#mylist li').removeClass('not-selected');        
    }
    else
    {
        $('#mylist li').removeClass('selected').addClass('not-selected');
        $(this).removeClass('not-selected').addClass('selected');
    }
});
于 2013-10-31T15:22:14.893 回答
1

与 jQuery 的许多事情一样,您可以在一行中完成。

$('#mylist').on('click', 'li', function () {
    $(this).toggleClass('selected').siblings().removeClass('selected');
});

我建议不要使用不同的not-selectedCSS 类。“未选择”是默认设置。

这使得 JavaScript 和 CSS 代码都更简单,并避免了“三态”情况,即第三个状态是既不是selected也不是的元素not-selected

如果您不想切换“选定”状态,请.addClass()使用.toggleClass().

http://jsfiddle.net/Aa2NW/

于 2013-10-31T15:29:50.753 回答
0

离开@Tim,我认为这就是您想要的多项选择:http: //jsfiddle.net/Dcwc5/

像这样更改您的javascript:

$('#mylist').on('click', 'li', function () {

   if ($(this).hasClass('selected'))
    {
        //clicked element was previously selected
        //remove his selected status
        $(this).removeClass('selected').addClass('not-selected');
        //check if other's are selected
        if($('#mylist li.selected').length == 0){
            $('#mylist li').removeClass('not-selected');  
        }
    }
    else if ($(this).hasClass('not-selected')){
        $(this).removeClass('not-selected').addClass('selected');
    }
    else
    {
        //elementw as newly selected
        //all li's remove selected, add not-selected
        $('#mylist li').removeClass('selected').addClass('not-selected');

        //remove not-selected from current element and add selected
        $(this).removeClass('not-selected').addClass('selected');
    }
});
于 2013-10-31T15:35:36.057 回答