替换部分URL

Replacing portions of the URL

本文关键字:URL 替换部      更新时间:2023-09-26

我有这个网站的链接:

http://example.com/example/index.html#page=page-1

我想检测URL的#page=page-1部分,并将其添加到http://example.com/example/indexcn.html当我点击链接时http://example.com/example/indexcn.html#page=page-1) 。

之所以这样做,是因为我想有一个双语网站,并在选项卡之间切换语言。

我看过onclick函数和window.location.pathname函数:

$("a.language").click(function(){
function reloadPageWithHash() {
var initialPage = window.location.pathname;
window.location.replace('http://example.com/#' + initialPage);
}
});

但我不确定该从哪里开始(注意window.location.pathname检测到"example/index.html#page=page-1",而不仅仅是标签)。

希望有人能帮我。(:

谢谢!

您可以使用window.location.hash只获取哈希部分。

例如:

$("a.language").click(function(){
    window.location.href = 'http://example.com/' + window.location.hash;
    return false; // prevent default action if any
});

注意:我已经删除了回调函数中的多余函数。

$(document).ready(function(){
$("a.lang").click(function(event){
event.preventDefault();
window.location.href = 'http://example.com' + window.location.hash;
});
});

四处玩耍,这对我来说很成功

您可以使用onhashchange来侦听对URL哈希的更改:

function locationHashChanged() {
    if (location.hash === "#page-1") {
        doSomething();
    }
}
window.onhashchange = locationHashChanged;

或者使用jQuery:

$(window).hashchange(myCallback);

你可以试试这个,这可能会有所帮助:

$(document).ready(function () {
    var thisUrl = window.location.href;
    var strOptions = thisUrl.split('#');
    var strQuerystring = strOptions[1];
    var strURL = 'http://example.com/example/indexcn.html' + strQueryString;
}