如何在javascript中更改当前URL?
在我的网站上:如何在javascript中更改当前URL?,javascript,Javascript,在我的网站上: http://mywebsite.com/1.html 我想使用 window.location.pathname 要获取url的最后一部分,请执行以下操作: 1.html 由于我的所有网页都是数字,我想在当前url中添加1,这样当我单击按钮时,它会将我重定向到下一页: var url = 'http://mywebsite.com/' + window.location.pathname; function nextImage (){ url = url + 1; }
http://mywebsite.com/1.html
我想使用
window.location.pathname
要获取url的最后一部分,请执行以下操作:
1.html
由于我的所有网页都是数字,我想在当前url中添加1,这样当我单击按钮时,它会将我重定向到下一页:
var url = 'http://mywebsite.com/' + window.location.pathname;
function nextImage (){
url = url + 1;
}
你知道为什么这不起作用吗?即使这不是一种很好的方法,也可以尝试以下提示: var url=必须首先是一个数字
function nextImage (){
url = url + 1;
location.href='http://mywebsite.com/' + url+'.html';
}
你要做的是在你的URL后面加上一个“1”(字符串)。如果您想将page 1.html链接到page 2.html,则需要从字符串中取出1,添加一个,然后重新组合字符串 为什么不这样做:
var url = 'http://mywebsite.com/1.html';
var pageNum = parseInt( url.split("/").pop(),10 );
var nextPage = 'http://mywebsite.com/'+(pageNum+1)+'.html';
window.location.href = nextImage();
在这种情况下,下一页将包含url。如果需要,应该可以很容易地将其放入函数中。您的示例不起作用,因为您试图将1添加到如下所示的字符串:“1.html”。这会让你得到这个“1.html1”,这不是你想要的。您必须先分离字符串的数字部分,然后将其转换为实际数字,然后才能对其进行数学运算。在得到一个实际数字后,您可以增加其值,然后将其与字符串的其余部分合并 您可以使用如下自定义替换函数来隔离原始URL的各个部分,并用递增的数字替换该数字:
function nextImage() {
return(window.location.href.replace(/(\d+)(\.html)$/, function(str, p1, p2) {
return((Number(p1) + 1) + p2);
}));
}
你可以这样称呼它:
var url = 'http://mywebsite.com/1.html';
var pageNum = parseInt( url.split("/").pop(),10 );
var nextPage = 'http://mywebsite.com/'+(pageNum+1)+'.html';
window.location.href = nextImage();
此处演示:
这将适用于任何以.html结尾的一系列数字结尾的URL,如果您需要稍微不同的URL形式,您可以调整正则表达式。这更为健壮:
mi = location.href.split(/(\d+)/);
no = mi.length - 2;
os = mi[no];
mi[no]++;
if ((mi[no] + '').length < os.length) mi[no] = os.match(/0+/) + mi[no];
location.href = mi.join('');
它支持带前导零的数字:
http://mywebsite.com/0001.html
您只是在url中添加了1。您需要增加文件名-#.html的数字部分。我猜他们希望您演示如何获取数字。