简体   繁体   中英

jQuery to get part of a url and apply it to the end of an existing link

I am creating a script for a Wordpress Multisite, to allow the user to switch between sites ie EN, FR, DE.

The link in the menu is structured as so:

<li class="en-link">
<a href="https://example.com" />EN</a>
</li>
<li class="fr-link">
<a href="https://example.com/fr" />FR</a>
</li>

I'd like the user to be able to switch back and forth between these sites. But this does not work for subpages obviously. So i need to be able to get everything infront of the first forward slash and apply it to these links.

This is what i have currently:

jQuery(function ($) {
var currentURL = (document.URL); 
var part = currentURL.split("/")[1];
$(".en-link a").attr('href', $(".en-link a").attr('href') + part);
$(".fr-link a").attr('href', $(".fr-link a").attr('href') + part); 
});

But to no avail. Any thoughts?

You can get the path from JavaScript's built-in Location , window.location.pathname.split('/')[1] will give you the first segment of the path, depending on your url this will be either "fr", "de" or "en"

This is what worked for me using jQuery

$(document).ready(function () {
var trail = window.location.href.substr(window.location.href.lastIndexOf("/")+1); 
$(".en-link").find('a').attr('href', $(".en-link").find('a').attr('href') + trail);
$(".fr-link").find('a').attr('href', $(".fr-link").find('a').attr('href') + trail); 
  }); 

But also need to counter for subpages for press and media sections:

jQuery(function ($) {
  $(document).ready(function () {
var trail = window.location.href.substr(window.location.href.lastIndexOf("/")+1);  
  var trailSub = window.location.href.substr(window.location.href.lastIndexOf("/")-5);  
    if (window.location.href.indexOf("press") != -1) {
$(".en-link").find('a').attr('href', $(".en-link").find('a').attr('href') + trailSub);
$(".fr-link").find('a').attr('href', $(".fr-link").find('a').attr('href') + trailSub); 
    }
    else if (window.location.href.indexOf("media") != -1) {
$(".en-link").find('a').attr('href', $(".en-link").find('a').attr('href') + trailSub);
$(".fr-link").find('a').attr('href', $(".fr-link").find('a').attr('href') + trailSub); 
    }
    else {
      $(".en-link").find('a').attr('href', $(".en-link").find('a').attr('href') + trail);
$(".fr-link").find('a').attr('href', $(".fr-link").find('a').attr('href') + trail); 
    }
  });
});

im sure this can be simplified, but have minified for now.

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