简体   繁体   中英

how to echo javascript generated value in href?

This is my javascript code below (Just to get current url)

 <html> <head> </head> <body onload="myFunction();"> <p id="myurl"></p> <script> function myFunction() { document.getElementById("myurl").innerHTML = window.location.host; } </script> </body> </html> 

And Now i want to use <p id="myurl"></p> as below:

 <a href="https://www.facebook.com/sharer/sharer.php?u=<p id="demo"></p>">Share on Facebook</a> <br> 

But as it cant be execured inside href="value"
Is there any way to do that with php or something else?

用这个 :-

 <a href="https://www.facebook.com/sharer/sharer.php?u=<?php echo $_SERVER['REQUEST_URI']; ?>">Share on Facebook</a> <br>

I'm assuming client only solution is needed here, server can be anything (PHP, ASP, etc.) All you've to do is to modify the href property of anchor tag. You can modify your code as -

var elm = document.getElementById("demo");
var URLBase = elm.getAttribute("href");
var fullURL = URLBase.window.location.host;
elm.setAttribute("href", fullURL);

With pure javascript (default url in href):

<a id="share_url" href="https://www.facebook.com/sharer/sharer.php?u=">Share on Facebook</a>

<script>
    function myFunction() {
        var el = document.getElementById("share_url");
        el.href += window.location.host;
    }
</script>

Demo: http://jsfiddle.net/Lrkjr23o/1/

Other way to create href attribute dynamically:

<a id="share_url">Share on Facebook</a>

<script>
    function myFunction() {
        var el = document.getElementById("share_url");
        el.href = 'https://www.facebook.com/sharer/sharer.php?u=';
        el.href += window.location.host;
    }
</script>

Demo: http://jsfiddle.net/Lrkjr23o/

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