简体   繁体   中英

JS not working as expected when selecting options from dropdown

Goal

  1. clicking on a member of the <ul> selects/deselects it.

  2. if class=allSearch is selected any other li's that are already selected are de-selected.

  3. if allSearch is selected and then notAllSearch is selected, allSearch is deselected.

Problem

Goal 3 is not working, which doesn't make sense to me because it should be (and is) basically the same code used in Goal 2.

Here's the code:

HTML

<ul class="menu vertical" id="searchMenu">
    <li id="allSearch" class="allSearch selected">All</li>
    <li id="notAllSearch" class="notAllSearch">User</li>
    <li id="notAllSearch" class="notAllSearch">Artists</li>
    <li id="notAllSearch" class="notAllSearch">Events</li>
</ul>

JS:

$(document).ready(function() {
$('#searchMenu li').click(function () {
    if ($(this).hasClass('selected')) {
        $(this).removeClass('selected');
        }
    else if ($(this).hasClass('notAllSearch')) {
        $('#allSearch').removeClass('selected')
        $(this).addClass('selected');
    }
    else if ($(this).hasClass('allSearch')) {
        $('#notAllSearch').removeClass('selected')
        $(this).addClass('selected');
    }
    else
        $(this).addClass('selected');
});
})

Try this : instead of ID work on CLASS for this

$(document).ready(function() {
$('#searchMenu li').click(function () {
    if ($(this).hasClass('selected')) {
        $(this).removeClass('selected');
    }
    else if ($(this).hasClass('notAllSearch')) {
        $('.allSearch').removeClass('selected')
        $(this).addClass('selected');
    }
    else if ($(this).hasClass('allSearch')) {
        $('.notAllSearch').removeClass('selected')
        $(this).addClass('selected');
        }
    else
        $(this).addClass('selected');
    });
});

Here is the pen to test

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM