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.
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.