简体   繁体   中英

Changing the color of an element in a ul on click, but keeping it when clicking on an element of another ul

there is a task to change the color of the li in the ul, but only in a specific ul, when you click on the li in another ul, the old li is not lost. How to implement this without Id, since UL are output through a loop and there can be an unlimited number of them.

 $('.list').on('click', 'li', function() { $('.list li').removeClass('active'); $(this).addClass('active'); });
 li { cursor: pointer; } li.active { color: red; }
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <ul class="list"> <li>1</li> <li>2</li> <li>3</li> <li>4</li> </ul> <ul class="list"> <li>5</li> <li>6</li> <li>7</li> <li>8</li> </ul>

You need to differentiate your uls in some way. I didn't understand why you can't use Ids but there are other options.

  1. add class of list1/list2 and only target the necessary list.

2.You could use:nth-child() in jQuery and CSS. So if you only wanted the action to occur when clicking on an li of the first ul you would do this:

 $('.list:nth-child(1)').on('click', 'li', function() { $('.list li').removeClass('active'); $(this).addClass('active'); });
 li { cursor: pointer; } li.active { color: red; }
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <ul class="list"> <li>1</li> <li>2</li> <li>3</li> <li>4</li> </ul> <ul class="list"> <li>5</li> <li>6</li> <li>7</li> <li>8</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