简体   繁体   中英

Jquery How to trigger function on without specifying events in the list

I have a list of items and can be removed by clicking.

I need the first item to be the highlight only when there is one item on the list. I have tried to do that by the click event. However, would it be possible to do it without.click()? (or any other events). The reason is that this list is dynamically interacting with other lists that the list item may change by other functions.

In other words, the list is dynamically changing, could jquery keep checking whether there is only one item on the list (without specifying specific event trigger)?

<ul id="container">
<li>1</li>
<li class="fixed">2</li>
<li>3</li>
<li class="fixed">4</li>
<li>5</li>
</ul>

$('#container').delegate('li', 'click', function() {
  $(this).remove();
});


$('#container').click(function(){
  if ($('#container').children().length == 1) {
    $("#container li:first-child" ).css( "background-color", "#fff2ac" );
  }
}

You can do this purely with CSS with a rule that checks if the li is both the :first-child AND the :last-child -

 .container li:first-child:last-child { background-color: red; }
 <h5>List With Many Items</h5> <ul class="container"> <li>1</li> <li class="fixed">2</li> <li>3</li> <li class="fixed">4</li> <li>5</li> </ul> <h5>List With One Item</h5> <ul class="container"> <li>1</li> </ul> <h5>List With Two Items</h5> <ul class="container"> <li>1</li> <li class="fixed">2</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