简体   繁体   中英

jQuery - Create link element and click it

I am trying to dynamically generate a link to Post a tweet on twitter and then click on it like this...

$("body").prepend("<a id=\"twitter_link\" href='https://twitter.com/intent/tweet'></a>");

$( "#twitter_link" ).click(function() {
  console.log( "Handler for .click() called." );
});

This is not working, where am i going wrong?

Your code is 99% done!

Your new a element doesn't have text

Important

The click event it's necessary if you need to execute a logic when the new link is clicked, otherwise, that event it's unnecessary.

 $("body").prepend("<a id=\\"twitter_link\\" href='https://twitter.com/intent/tweet'>Hello World</a>"); $( "#twitter_link" ).click(function(e) { e.preventDefault(); //This is just to show your logic is working! console.log( "Handler for .click() called." ); location.href = this.href; //This is to redirect to the specific page after any previous executed logic. }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 

Resource

you can also try creating the element first, adding the event listener and then appending to the body

var $a = $("<a id=\"twitter_link\" href='#'>test</a>" );

$a.click(function(e) {
  e.preventDefault();
  console.log( "Handler for .click() called." );
});

$("body").prepend($a);

If you actually want to automatically click the link, you have to call .click() on the element -- you're binding a click handler. Here's an example without jQuery adapted from a project I'm working on:

 function clickLink(url) { let anchor = document.createElement('a'); anchor.href = url; document.body.appendChild(anchor); // Firefox requires us to actually insert the element into the DOM before we can click it anchor.click(); document.body.removeChild(anchor); } clickLink('https://stackoverflow.com') 

Watch your devtools console though, because if you try linking to another domain you might get this error:

Refused to display ' https://www.google.ca/?gfe_rd=cr&dcr=0&ei=--R8WpqeLpTM8AeZoYbgAg ' in a frame because it set 'X-Frame-Options' to 'sameorigin'.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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