JQuery trigger click for function with e.target

I had problems with jQuery .trigger() in the past, sometimes it works, while others do not. It usually breaks when I need it to do something like this ...

HTML

 <div class="list"> <a href="#" class="one">one</a> <a href="#" class="two">two</a> <a href="#" class="three">three</a> </div> <p class="output"></p> 

Js

 $(document).ready(function() { $('.two').trigger('click'); $('.list a').click(function(e){ e.preventDefault(); $text = $(e.target).text(); $('.output').text($text); }); }); 

script: http://jsfiddle.net/7pup2/

+4
source share
1 answer

You need to register the handler first and then fire the event

he should be

 $(document).ready(function() { $('.list a').click(function(e){ e.preventDefault(); $text = $(e.target).text(); $('.output').text($text); }); $('.two').trigger('click'); }); 
+4
source

Source: https://habr.com/ru/post/1495874/


All Articles