0

Can I emulate a click on a finished document with jQuery?

I have this code :

<a href="javascript:void(0)" id="0" class="hp_nav_label">0</a> <a href="javascript:void(0)" id="1" class="hp_nav_label">1</a> <a href="javascript:void(0)" id="2" class="hp_nav_label">2</a> <a href="javascript:void(0)" id="3" class="hp_nav_label">3</a> <a href="javascript:void(0)" id="4" class="hp_nav_label">4</a> $('.hp_nav_label').click(function() { alert($(this).attr('id')); }); 

When I click on each link, I display its identifier.

Now, I would like to automatically β€œprocess” the link with id=2 on the finished document, without β€œclicking” it.

So, having a kind of emulation on this link. Is this possible with jQuery?

+4
source share
5 answers

To trigger an event, simply call the corresponding event function in jQuery on the element, without a specific handler function, for example:

 $("#2").click(); 

Or there is also trigger() that accepts the type of event as a parameter:

 $("#2").trigger('click'); 

However, it is worth noting that Id attributes starting with numbers are invalid, so you will most likely have to change your identifiers so that they can work properly.

I updated your script to fix the identifiers and show the above code here

+8
source

You can use trigger :

 $('#2').trigger('click'); 

http://api.jquery.com/trigger/

+1
source

Yes, .click() methods are also used to trigger the click event.

 $('#2').click(); 

This is a shorthand for $('#2').trigger('click'); .

Also note that the identifier cannot begin with a digit.

JQuery documentation for click()

JQuery documentation for trigger()

+1
source

Usually you can just call the same function as click calls.

Do you need something like $ (this) to populate?

+1
source

You can use triggerHandler for this:

 $("#2").triggerHandler("click"); 
+1
source

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


All Articles