Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/performance/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
使用Javascript操作url在子文件夹中选择语言_Javascript - Fatal编程技术网

使用Javascript操作url在子文件夹中选择语言

使用Javascript操作url在子文件夹中选择语言,javascript,Javascript,我想创建一个小菜单来更改静态站点的语言。有两种语言,德语和英语,德语是我项目的基本文件夹中的主要语言。我将英文版本放入子文件夹/en。现在,我希望能够在语言之间切换,而无需将绝对URL硬编码到每个htlm文件中,这就是我编写一些JS的原因。但我认为这只是一个肮脏的解决方案: 例如,两个索引文件的URL如下所示: 德语: 中文: 选择语言的html,简化为: <h3>Please select your language</h3> <button class=

我想创建一个小菜单来更改静态站点的语言。有两种语言,德语和英语,德语是我项目的基本文件夹中的主要语言。我将英文版本放入子文件夹/en。现在,我希望能够在语言之间切换,而无需将绝对URL硬编码到每个htlm文件中,这就是我编写一些JS的原因。但我认为这只是一个肮脏的解决方案:

例如,两个索引文件的URL如下所示:

德语:
中文:

选择语言的html,简化为:

<h3>Please select your language</h3>
    <button class="deutsch">Deutsch</button>
    <button class="english">English</button>
丑陋的部分在“var基础”内。我需要复制/filename.html之前的url,除了将整个路径拆分,然后在有无语言目录的情况下将所有内容重新组合在一起,我没有别的想法。它工作得很好,但对我来说,这看起来真的很麻烦


有人能推荐一个更好的方法来达到同样的效果吗?

经过一个小时的测试,我找到了一个完美的解决方案:

var path = window.location.href;
// simply always removes the /en folder from the base url
var base = path.match(/^.*[\\\/]/)[0].replace(/(\/en)/, '');
var filename = path.replace(/^.*[\\\/]/, '');

$('.english').click(function(){
    window.location.href = base + 'en/' + filename;
});

$('.deutsch').click(function(){
    window.location.href = base + '' + filename;
});
var path = window.location.href;
// simply always removes the /en folder from the base url
var base = path.match(/^.*[\\\/]/)[0].replace(/(\/en)/, '');
var filename = path.replace(/^.*[\\\/]/, '');

$('.english').click(function(){
    window.location.href = base + 'en/' + filename;
});

$('.deutsch').click(function(){
    window.location.href = base + '' + filename;
});