简体   繁体   中英

how to get variable's value from URL and pass to all the links on the whole site?

I am trying to get a variable from a URL, for example if the users can link to this page: www.example.com?var1=blabla&var2=blabla and there are many links on this site www.example.com . What I want is no matter where my users click, they will always see the link appended with 2 variables they got from this link www.example.com?var1=blabla&var2=blabla for example: if there is another link

<a href="www.example.com/page1.php"/>Go to page1</a>

on www.example.com?var1=blabla&var2=blabla , they will go to page www.example.com/page1.php?var1=blabla&var2=blabla .
This is my code:

<script type="text/javascript">
$(document).ready(function() {
    var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1);
    var links = $('a');
    links.each(function(){
    var curLink=$(this);
    var href = curLink.attr('href');
    var newhref = href +'?'+ hashes; 
    curLink.attr('href',newhref);
    });
});
</script>

My question is: I can only make all the links on the same page append those 2 variable. If the users go to another page, it won't do the same thing, because there is no script on it... but I can't add same script on every pages... And another question, I want to clear the things after question mark and append the new ones.. is that possible to do that?

Thanks!

Your code looks good to me. And from your question it appears that your problems lie outside this.

My question is: I can only make all the links on the same page append those 2 variable. If the users go to another page, it won't do the same thing, because there is no script on it... but I can't add same script on every pages...

If you can't run your script on every page then you can't modify the url's. You will need to do it server side. If you can't do it server side then you are out of luck.

And another question, I want to clear the things after question mark and append the new ones.. is that possible to do that?

Yes, that is certainly possible. To strip the querystring use the following code.

var strippedHREF = window.location.href.substring(0, window.location.href.indexOf('?'));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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