简体   繁体   中英

Printing a javascript variable in php echo

To clarify:

I have an echo statement as follows:

 $striptitle .= ' - <a onclick="getnewurl();" href="'.SGLink::album($aid). '">'. $namek .'</a></h1>
<a href="https://twitter.com/share" class="twitter-share-button" data-lang="en" data-via="jb_thehot" data-text="Pictures of '. $hashfinal .'" teens>Tweet</a>
<script>!function(d,s,id){var js,fjs=d.getElementsByTagName(s)[0];if(!d.getElementById(id)){js=d.createElement(s);js.id=id;js.src="//platform.twitter.com/widgets.js";fjs.parentNode.insertBefore(js,fjs);}}(document,"script","twitter-wjs");</script>';

echo $striptitle ;

The onclick does this:

<script type="text/javascript">
function getnewurl()
{
var url = document.URL;
alert( url );
}
</script>

What I need is essentially to add the my anchor tag a data-url="INSERT_VAR_URL_HERE"

Is that possible?

Let me know if this isn't clear enough Thanks!

Edit: to clarify, the alert in the function is only for testing. What I need is to be able to use the variable obtained in the function, in the same $striptitle variable.

My problem is that the url changes with AJAX, and the twitter button's data-url does not get updated. I was hoping to be able to get the new url by getting it everytime it is clicked. If there are other ways to do that, I'm open to suggestions!

Why not pass it as an argument?

$striptitle .= " - <a onclick=\"getnewurl('URL-HERE');\"...>";

Then in your script:

<script>
    function getnewurl(url) {
        alert(url);
    }
</script>

Building on @Kolink's answer one way to not repeat the url in two places you could generate the link as:

<a onclick="getnewurl(this);" href="...">

then your JS could look like:

function getnewurl(link) {
    link.setAttribute('data-url', location.href);
}

EDIT apparently jQuery.data doesn't update the dom properly, but setAttribute does

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