単に完全なURLを取得して/en/
、/chi/
またはその逆に置き換える場合は、以下のコードを使用してください。
HTML
<span onclick="SwitchLang()">View [Some other Language]</span>
JavaScript
function SwitchLang() {
//Does URL contain "/en/"?
if(window.location.href.indexOf("/en/") != -1) {
//URL contain "/en/", replace with "/chi/"
window.location.href = window.location.href.replace("/en/", "/chi/");
}
//Does URL contain "/chi/"?
else if(window.location.href.indexOf("/chi/") != -1) {
//URL contain "/chi/", replace with "/en/"
window.location.href = window.location.href.replace("/chi/", "/en/");
}
}
または、もう少し簡潔(コメントなしのバージョン)
function SwitchLang() {
if(window.location.href.indexOf("/en/") != -1)
window.location.href = window.location.href.replace("/en/", "/chi/");
else if(window.location.href.indexOf("/chi/") != -1)
window.location.href = window.location.href.replace("/chi/", "/en/");
}
注: JSでは、を変更するwindow.location.href
と、新しいURLが自動的に読み込まれます。
これがあなたが遊ぶための実用的なフィドルです。