简体   繁体   中英

Change li Background Colour In Javascript

I wonder if someone can please advise me how I can do the following?

I have the below JS which changes the background colour of an li based on id (I'm using the li as buttons). When the li is clicked the background turns white. Can someone please tell me what I should add to return all other li elements to their original colour?

Many thanks

 $(function () {
            $("li").click(function (e) {
                document.getElementById(e.target.id).style.backgroundColor = "#fff";
            });
        });

You can do this more easily with a class:

 $('li').on('click', function() { $('.whitebg').removeClass('whitebg'); $(this).addClass('whitebg'); }); 
 body { background: deepskyblue; } li { background: green; display: inline-block; cursor: pointer; padding: 4px 8px; } .whitebg { background: white; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <ul> <li>Item 1</li> <li>Item 2</li> <li>Item 3</li> <li>Item 4</li> <li>Item 5</li> </ul> 

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