简体   繁体   English

如何动态更改href链接?

[英]how do I change the href link dynamically?

how do I change the href link dynamically ? 如何动态更改href链接?

<link rel="image_src" href="" id="ShareImageID"/>

so that when someone share the web page on facebook the thumbnail shows specific image from that link tag. 这样,当有人在Facebook上共享网页时,缩略图会显示该链接标签中的特定图像。

I do not want to change the link for each page. 我不想更改每个页面的链接。

I also tried to use the og:image, it worked but I was not able to change it dynamically. 我也尝试使用og:image,它可以工作,但是我无法动态更改它。 I also tried this 我也尝试过

<script>
var ShareImageIdVar = location.href.match(/\d+/);
document.getElementById('ShareImageID').href = 
        "http://www.mysite.com/Images/"+ ShareImageIdVar +".jpg";
</script>

but it is not working :( facebook is still choosing another thumbnail. a random one. 但它不起作用:( Facebook仍在选择另一个缩略图。是随机的。

You cannot change the Facebook image with JavaScript. 您无法使用JavaScript更改Facebook图像。 When you share a link on Facebook, Facebook scrapes the page looking for images. 当您在Facebook上共享链接时,Facebook会刮取页面以查找图像。 This scrape doesn't run JavaScript. 此刮擦无法运行JavaScript。

You will need to change the image server side, possibly with PHP. 您可能需要使用PHP更改图像服务器端。

If you want Facebook to select the proper image when your link is posted, you need to have the proper OpenGraph image chosen in the <head> of your php file. 如果您希望Facebook在链接发布后选择适当的图像,则需要在php文件的<head>中选择适当的OpenGraph图像。

you can read more about open graph here https://developers.facebook.com/docs/opengraph/ 您可以在这里阅读有关开放图的更多信息https://developers.facebook.com/docs/opengraph/

Make sure to have all the necessary OG elements, for it to work properly. 确保具有所有必需的OG元素,以使其正常工作。

Since you are asking about the image, you should have something like this: 由于您正在询问图像,因此应该具有以下内容:

 <head>
 <meta property="og:image" content="/images/pageimage.png" />
 </head>

To dynamically alter it, just use an echo that is specific to the php page edit/like this: 要动态更改它,只需使用特定于php页面edit / echo ,如下所示:

<meta property="og:image" content="<?php echo "$imageurl" ?> />

just set the variable $imageurl specifically on each php page. 只需在每个php页面上专门设置变量$imageurl

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

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