简体   繁体   中英

How do I get a URL parameter and add it to a link on the same page using javascript?

I have a page on my website where users can visit to access the website in the language they need.

For example:

<ul class="locale-list">
<li><a title="Deutsch" href="/de-de/" locale="de">Deutsch</a></li>
<li><a title="English" href="/en-en" locale=en">English</a></li>
<li><a title="French" href="/fr-fr/" locale="fr">Français</a></li>
</div>

Those links will lead to the homepage in that language.

What I'm trying to do is make it so if someone visits this page from an existing page on the website, they are sent BACK to the previous page via this URL parameter:

example.com/languages?target=[page-slug]"

The reason for this is because if you a user is viewing the page "Acme" and needs to change the language, the user should click over to the language selector page, click on which which one they want, and it will kick them back to the "Acme" page so they can review the page in that language.

My thought here is that I can snag the 'target' parameter value and have the links update like this:

<ul class="locale-list">
<li><a title="Deutsch" href="/de-de/[page-slug]" locale="de">Deutsch</a></li>
<li><a title="English" href="/en-en/[page-slug]" locale=en">English</a></li>
<li><a title="French" href="/fr-fr/[page-slug]" locale="fr">Français</a></li>
</div>

This would send the user back to the page they were on, but in the language they need.

I found a solution for this using PHP...

<?php if (isset($_GET['target'])) {?><?php echo $_GET['target']; ?><?php } ?>

...but the website has to be static and can't support the PHP solution.

Is there a similar way to do this with javascript?

Use this code. It may help you.

$(document).ready(function(){
    $("button").click(function(){
        var pageURL = $(location).attr("href");
          alert(pageURL);
    });
});

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