简体   繁体   中英

Javascript var in href tag

Hi I would like to put a dynamic link in a href tag with window.location.href

How can I do this?

<a href="https://twitter.com/share?url="+ <script> window.location.href </script>+ "&text=!" target="_blank">
  Twitter
</a>

You could give the a an id and look it up by that.

 document.getElementById('foo').setAttribute('href', `https://twitter.com/share?url="${window.location.href}&text=!`);
 <a id="foo" target="_blank"> Twitter </a>

You can try the following way:

 var el = document.querySelector('a'); el.href = el.href+window.location.href + '&text=!';
 <a href="https://twitter.com/share?url=" target="_blank"> Twitter </a>

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