Programmatically press the href button and add the code

I would like to dynamically add the href element (to open the jnlp file) and then continue the caller's workflow, for example, simply by running console.log .

So far my code is:

 $('<a id="tmplink" />') .attr('href', '/open_my.jnlp') .text('LINK') .appendTo('body') .get(0) .click(function(e) { console.log('aaaa'); // <-- this is never reached }); 

The jnlp file opens, but the browser console, at least in Firefox, is updated / cleared, and console.log never reached.

+5
source share
2 answers

Your code will work fine after setting these two points:

  • No need to use .get(0) as it will return an HTML element, for example:

     <a id="tmplink" href="/open_my.jnlp">LINK</a> 

This way you cannot attach the click event to ( html ), instead you can directly bind the click() event.

  1. You must prevent redirection with .preventDefault() to see the console log:

     $('<a id="tmplink" />') .attr('href', '/open_my.jnlp') .text('LINK') .appendTo('body') .click(function(e) { e.preventDefault(); console.log('anchor clicked'); }); 

Hope this helps.

 $('<a id="tmplink" />') .attr('href', '/open_my.jnlp') .text('LINK') .appendTo('body') .click(function(e) { e.preventDefault(); console.log('anchor clicked'); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
+2
source

Your code will work if you add a click event listener separately, under the prompt.

Example:

 $(document).ready(function(){ $('<a id="tmplink" />') .attr('href', '/open_my.jnlp') .text('LINK') .appendTo('body') .get(0); $('#tmplink').click(function(){ console.log('aaaa'); }); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
0
source

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


All Articles