【问题标题】:Switching to relative location切换到相对位置
【发布时间】:2018-06-08 11:33:29
【问题描述】:

嗨,不知道是否有人能指出我正确的方向。

我正在寻找一些代码,我可以将这些代码放在一个链接上,该链接将转到当前页面的 url,但在一个单独的文件夹中,或者在 url 中添加一个语言标识符。

例如,如果有人在 FAQ.aspx 上,他们点击菜单中的意大利语链接,它会将他们发送到 it-FAQ.aspx 或 /it/FAQ.aspx,其他页面也是如此。

这有意义吗?有没有可能,有人可以指出我的方向吗

提前致谢!

【问题讨论】:

  • 有可能,你需要从浏览器获取第一个实际的 url 并将国家代码放在开头。

标签: javascript jquery url


【解决方案1】:

试试这样的:

获取当前url的第一个路径名,然后将语言代码放在前面并用jquery更改链接的href:

<html>
 <a class="switch_language" data-country-code="it" href="">Italian</a>
 <a class="switch_language" data-country-code="de" href="">German</a>

还有……

<script>
$('.switch_language').each(function() {
 $(this).attr('href', $(this).attr('data-country-code') + '/' + location.pathname);
});

您的语言链接的网址将如下所示

/it/faq.aspx
/de/faq.aspx

【讨论】:

  • 是否可以修改它,因为目前它将所有子文件夹都放在新的 url 中;例如,页面位于:domain.com/subsite1/subsite2/pages/faq.aspx 使用上面的脚本转到 domain.com/subsite1/subsite2/pages/de//subsite1/subsite2/pages/faq.aspx所以它会再次添加所有这些子站点,我希望它采用的 url 路径是:domain.com/subsite1/subsite2/de/pages/faq.aspx 这有意义吗?
【解决方案2】:

使用data 属性,您可以在链接上存储“要添加到URL 的部分”。您可以使用.data() 方法阅读它。

那么...如果你用/分割实际的URL,你可以重新组装它并插入要添加的部分。

此脚本适用于任何页面。

$(".menu .lang").on("click",function(){
  
  // Get the actual page URL
  var thisPage = location.href;
  console.log(thisPage);
  
  // Split the URL by the "/"
  var splitted = thisPage.split("/");
  var splittedLength = splitted.length;
  
  // Get the data-lang value
  var insert = $(this).data("lang");
  
  // Re-assemble the URL except the last part
  var destination="";
  for (i=0;i<splittedLength-1;i++){
    destination += splitted[i]+"/";
  }
  
  // Add the part to "insert" and last part of the URL
  destination += insert+"/"+splitted[splittedLength-1];
  
  // OR
  // destination += insert+"-"+splitted[splittedLength-1];  // See explanation below the snippet.
   
  // Go to that page!
  console.log(destination);
  //location.assign(destination);  // Commented for this demo...
  
});
.menu a{
  display:block;
  text-decoration:underline;
  cursor:pointer;
  color:blue;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<h1>FAQ</h1>
<div class="menu">
  <a class="lang" data-lang="it">Italiano</a>
  <a class="lang" data-lang="en">english</a>
  <a class="lang" data-lang-"fr">Français</a>
</div>

这里,语言参数添加在/ 之间,就像它是一个目录...但是您可以轻松地将它添加到页面名称中,例如它-FAQ.aspx。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-02-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-04-09
    相关资源
    最近更新 更多