简体   繁体   中英

jQuery specific event trigger

I have a unordered list with an event handler attached using jQuery

<ul class='menu'>
  <li id='1'>Home</li>
  <li id='2'>item 1</li>
  <li id='3'>item 2</li>
</ul>

$('.menu').on('click','li',function(){
  console.log($(this).attr('id'));
  // do navigation stuff
});

What I want to do is have an event trigger that when I return to this list it automatically selects the option that I selected previously. I have everything else working except this trigger. Any help would be great in guiding me in the right direction. Thanks in advance.

You can save your selection in a variable and use that to trigger the click on the correct <li> :

var lastSelected = 1;

$('.menu').on('click','li',function(){
  console.log($(this).attr('id'));
  // do navigation stuff

  lastSelected = $(this).attr('id'); //save the id
});

To trigger the event later, use:

$('#'+lastSelected).trigger('click');

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