JQuery trigger click vs click ()?

I have this simple code: here

$(".btn").on('click',function () { $(".a").trigger('click'); }); $(".btn2").on('click',function () { $(".a")[0].click(); }); 

I am trying to simulate clicking on the Anchor.

But when I use jQuery trigger it doesn't work (why?)

When I use "jsobj".click() func, it works.

After reading the jQuery documentation, I see no reason why this should not.

Reference?

PS: I use Chrome.

+6
source share
3 answers

Actually $(".a").trigger('click'); fires a click event, but this does not mean that he clicks on the link, instead he will execute the event handler if you already have one, i.e.

 $(".btn, .btn2").on('click',function () { $($(".a")[0]).trigger('click'); // first element }); $(".a").on('click', function (e){ alert(e.target); });​ 

The above example will trigger the click a event and execute the handler (anonymous function) that has already been registered for this event using

 $(".a").on('click', function (e){...}); 

Demo.

+6
source

because $(".a")[0] returns a raw JavaScript node, you cannot use jQuery object methods for it.

+3
source

This is because jQuery .trigger() does not .trigger() its own events. Try this, for example, in a script:

 $(".btn").on('click',function () { $(".a").trigger('click'); }); $(".a").click(function(){alert('triggered!')}); 

When you create a costume handler using jQuery, the THEN event will be fired using the .trigger() method.

Update: This is pretty interesting, it seems to only happen with <a> AND tags with href . check this

+2
source

All Articles