简体   繁体   中英

How to change background color of the selected item in a list

How do I change the background color of the selected item in a list. I'm not sure whether this is done in the CSS or my script.

<script id="INLINE_PEN_JS_ID">
$(document).ready(function () {

  $('.accordion-list > li > .answer').hide();

  $('.accordion-list > li').click(function () {
    if ($(this).hasClass("active")) {
                                      
       if (event.target.closest('a')) {
        // an <a> was clicked
        return;
        }   
      $(this).removeClass("active").find(".answer").slideUp();
      
    } else {
        
      $(".accordion-list > li.active .answer").slideUp();
      $(".accordion-list > li.active").removeClass("active");
      $(this).addClass("active").find(".answer").slideDown();
      $(".accordion-list > li.style.backgroundColor = "red";
    }
    return false;
  });

});
</script>

Consider the following.

 $(function() { $('.accordion-list > li >.answer').hide(); $('.accordion-list > li').click(function(event) { if ($(this).hasClass("active")) { if ($("a", this).length && $(event.target).is("a")) { // <LI> contains <A> && <A> was clicked return; } $(this).removeClass("active").find(".answer").slideUp(); } else { $(".accordion-list > li.active.answer").slideUp(); $(".accordion-list > li.active").removeClass("active"); $(this).addClass("active").find(".answer").slideDown(); } return false; }); });
 .accordion-list>li { height: 60px; padding: 20px; }.accordion-list>li.active { background-color: red; }
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <ul class="accordion-list"> <li>Item 1</li> <li>Item 2</li> <li>Item 3</li> <li class="active"><i class="answer"></i>Item 4</li> <li>Item 5</li> </ul>

As you did not provide an example, I had to make some guesses. You can see that this is using both CSS and jQuery to help highlight the targeted list item.

The closest() method traverses the Element and its parents (heading toward the document root) until it finds a node that matches the provided selector string. Will return itself or the matching ancestor. If no such element exists, it returns null .

See more: https://developer.mozilla.org/en-US/docs/Web/API/Element/closest

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