简体   繁体   English

jQuery特定事件触发器

[英]jQuery specific event trigger

I have a unordered list with an event handler attached using jQuery 我有一个无序列表,其中使用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> : 您可以将选择保存在变量中,并使用该选项触发正确<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');

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM