简体   繁体   English

在php echo中打印一个javascript变量

[英]Printing a javascript variable in php echo

To clarify: 澄清:

I have an echo statement as follows: 我有一个echo语句,如下所示:

 $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: onclick会执行以下操作:

<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" 实际上,我需要的是将我的定位标记添加到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. 我需要的是能够在同一$ striptitle变量中使用在函数中获得的变量。

My problem is that the url changes with AJAX, and the twitter button's data-url does not get updated. 我的问题是URL随AJAX更改,并且twitter按钮的数据URL不会更新。 I was hoping to be able to get the new url by getting it everytime it is clicked. 我希望能够通过每次单击获得新的URL。 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: 建立在@Kolink答案的一种不在两个位置重复URL的方式上,您可以将链接生成为:

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

then your JS could look like: 那么您的JS可能看起来像:

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

EDIT apparently jQuery.data doesn't update the dom properly, but setAttribute does 编辑显然jQuery.data不能正确更新dom,但是setAttribute可以

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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