将javascript变量附加到两个HTML链接 [英] Append a javascript variable to two HTML links
问题描述
我有以下脚本:
<script>
window.onload = function setHref(){
var affglcid = <?php echo json_encode($kws); ?>;
var oldLink=document.getElementById('link').href;
document.getElementById('link').setAttribute('href', oldLink+affglcid);
var oldLink1=document.getElementById('link2').href;
document.getElementById('link2').setAttribute('href', oldLink1+affglcid);
}
</script>
并且:
<a id="link" href="oursite.com/">Link</a>
<a id="link2" href="othersite.com/">Link</a>
首先,它需要一个PHP变量:
First, it takes a PHP variable:
var affglcid = <?php echo json_encode($kws); ?>;
然后它将变量附加到链接的末尾:
Then it appends the variable at the end of a link:
var oldLink=document.getElementById('link').href;
document.getElementById('link').setAttribute('href', oldLink+affglcid);
它应该对另一个链接做同样的事情:
It should do the same for another link:
var oldLink1=document.getElementById('link2').href;
document.getElementById('link2').setAttribute('href', oldLink1+affglcid);
所以,如果$ kw = xy那么第一个链接应该是oursite.com/xy并且第二个othersite.com/xy但它只适用于其他站点链接。用于此的代码如下:
So, if $kw=xy then the first link should be "oursite.com/xy" and the second one "othersite.com/xy" but it only works on the other site link. The code used for that is the following:
<a id="link" href="oursite.com/">Link</a>
<a id="link2" href="othersite.com/">Link</a
任何想法有什么问题?
推荐答案
我注意到你的网址不正确,他们应该以http: //或https://
I noticed that your URLs not correct, they should start with "http://" or "https://"
<a id="link" href="http://oursite.com/">Link</a>
<a id="link2" href="http://othersite.com/">Link</a>
即使您不想添加协议,也应至少使用//oursite.com,否则它将被视为相对URL,它会在您当前的URL前面附加此URL并尝试打开
Even if you don't want to add protocol, you should atleast use //oursite.com, otherwise it'll be considered as relative URL which will append this URL in front of your current URL and try to open that
这篇关于将javascript变量附加到两个HTML链接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!