简体   繁体   English

将[URL]和[TITLE]替换为当前的URL和标题

[英]Replace [URL] and [TITLE] with current url and title

I have my mata tags at the top of each page: 我的mata标签位于每个页面的顶部:

<meta property="url" content="http://stackoverflow.com" />
<meta property="title" content="MY PAGE" />

I have multiple social media svgs I want to link to the current url and title. 我有多个社交媒体svg,我想链接到当前的网址和标题。 I have the correct queries for them but I want to add the url and title in dynamically. 我对他们有正确的查询,但我想动态添加url和标题。 So Facebook looks like: 因此,Facebook看起来像:

<a href="http://www.facebook.com/sharer/sharer.php?u=[URL]&title=[TITLE]"><img src="images/logo/facebook.svg"></a>

I think this can be done by Javascript/PHP but whats the best way? 我认为这可以通过Javascript / PHP完成,但是最好的方法是什么?

You are correct, this can be done with either PHP OR JavaScript. 您是正确的,可以使用PHP或JavaScript来完成。

PHP Method PHP方法

One method of doing this in PHP would be to create a $title and $url variable for each page: 在PHP中执行此操作的一种方法是为每个页面创建$ title和$ url变量:

<head>
<?php
    $metaUrl = "http://stackoverflow.com";
    $metaTitle = "MY PAGE";
?>

And refer them in your meta tags and anchor (note that I am using quick echo notation for echoing the PHP variables, this won't work on older PHP versions where full notation must be used): 并在您的meta标记和锚点中引用它们(请注意,我使用快速回显符号来回显PHP变量,这在必须使用完整符号的旧版PHP上将无法使用):

<meta property="url" content="<?=$metaUrl?>" />
<meta property="title" content="<?=$metaTitle?>" />
</head>

<body>
    <a href="http://www.facebook.com/sharer/sharer.php?u=<?=$metaUrl?>&title=<?=$metaTitle?>">
        <img src="images/logo/facebook.svg">
    </a>
</body>

JavaScript Method JavaScript方法

There is a simple way of doing this via JavaScript as well. 还有一种通过JavaScript进行此操作的简单方法。 First give your anchor an ID so we can easily find it in the DOM: 首先给您的锚定一个ID,以便我们可以在DOM中轻松找到它:

<a id="fb-sharer" href="http://www.facebook.com/sharer/sharer.php?u=[URL]&title=[TITLE]"><img src="images/logo/facebook.svg"></a>

Now in your script, get the title and url via the DOM document object: 现在,在脚本中,通过DOM文档对象获取标题和URL:

var title = document.title;
var url = document.URL;

Find your anchor in the DOM and set the href value with the variables: 在DOM中找到锚点,并使用变量设置href值:

var anchor = document.getElementById("fb-sharer");
var link = "http://www.facebook.com/sharer/sharer.php?u=" + url 
           + "&title=" + title;
anchor.setAttribute("href", link);

You can also use JavaScript to write the entire element in one go, throw this where ever your anchor should be: 您还可以使用JavaScript一次性编写整个元素,将其扔到您的锚点应该位于的位置:

<script>
    var title = document.title;
    var url = document.URL;
    document.write('<a id="fb-sharer"'
                  + 'href="http://www.facebook.com/sharer/sharer.php?u="' + url 
                  + '&title=' + title 
                  + '><img src="images/logo/facebook.svg"></a>');
</script>

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

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