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