Javascript 替换URL的某些部分
我有这个网站的链接: 我想检测URL的#page=page-1部分,并在单击链接时将其添加到 这样做的原因是因为我想有一个双语网站,并切换标签之间的语言 我已经介绍了onclick函数和window.location.pathname函数:Javascript 替换URL的某些部分,javascript,jquery,Javascript,Jquery,我有这个网站的链接: 我想检测URL的#page=page-1部分,并在单击链接时将其添加到 这样做的原因是因为我想有一个双语网站,并切换标签之间的语言 我已经介绍了onclick函数和window.location.pathname函数: $("a.language").click(function(){ function reloadPageWithHash() { var initialPage = window.location.pathname; window.location.re
$("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',而不仅仅是hashtag)
希望有人能帮我。(:
谢谢!您可以使用
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;
});
});
玩过之后,我就明白了。(:你可以用它来监听对URL哈希的更改:
function locationHashChanged() {
if (location.hash === "#page-1") {
doSomething();
}
}
window.onhashchange = locationHashChanged;
或者使用jQuery:
$(window).hashchange(myCallback);
您可以试试这个,这可能会有帮助:
$(文档).ready(函数(){
var thisUrl=window.location.href;
var strOptions=thisUrl.split(“#”);
var strQuerystring=strOptions[1];
var strURL='1〕http://example.com/example/indexcn.html“+strQueryString;
}
谢谢你的回答!虽然它似乎不起作用;但我无法让它将哈希标记固定到URL上。好吧,它应该能够检测到哈希部分,即使它是由于链接单击而动态添加到URL上的。添加信息-我添加了代码,但它似乎并没有阻止默认链接操作:默认链接是index-cn.html,Javascript链接是,但它指向index-cn.html