Append a Javascript variable to two HTML links

梦想与她 提交于 2019-12-11 20:04:28

问题


I have the following scripts:

<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> 

And:

<a id="link" href="oursite.com/">Link</a>
<a id="link2" href="othersite.com/">Link</a>

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);

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

Any ideas what's wrong?


回答1:


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>

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



来源:https://stackoverflow.com/questions/49911503/append-a-javascript-variable-to-two-html-links

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!