如何在javascript中更改当前URL? [英] How to change the current URL in javascript?

查看:85
本文介绍了如何在javascript中更改当前URL?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的网站上:

http://mywebsite.com/1.html

我想使用

window.location.pathname

获取网址的最后部分:

1.html

和由于我的所有网页都有数字,我想在当前网址中添加1,这样当我点击一个按钮时,它会将我重定向到下一页:

and since I have all my webpages in numbers I want to add 1 to the current url so that when I click a button it will redirect me to the next page:

var url = 'http://mywebsite.com/' + window.location.pathname;
function nextImage (){
url = url + 1;  
}

为什么这不起作用?

推荐答案

您的示例无效,因为您尝试将1添加到如下所示的字符串:1.html。这只会让你得到这个1.html1,这不是你想要的。您必须隔离字符串的数字部分,然后将其转换为实际数字,然后才能对其进行数学运算。在获得实际数字后,您可以增加其值,然后将其与字符串的其余部分合并。

Your example wasn't working because you are trying to add 1 to a string that looks like this: "1.html". That will just get you this "1.html1" which is not what you want. You have to isolate the numeric part of the string and then convert it to an actual number before you can do math on it. After getting it to an actual number, you can then increase its value and then combine it back with the rest of the string.

您可以使用这样的自定义替换函数隔离原始URL的各个部分并用增加的数字替换该数字:

You can use a custom replace function like this to isolate the various pieces of the original URL and replace the number with an incremented number:

function nextImage() {
    return(window.location.href.replace(/(\d+)(\.html)$/, function(str, p1, p2) {
        return((Number(p1) + 1) + p2);
    }));
}

然后你可以这样打电话:

You can then call it like this:

window.location.href = nextImage();

在这里演示: http://jsfiddle.net/jfriend00/3VPEq/

这适用于任何以一系列数字后跟.html结尾的URL如果你需要一个稍微不同的URL表单,你可以调整正则表达式。

This will work for any URL that ends in some series of digits followed by .html and if you needed a slightly different URL form, you could just tweak the regular expression.

这篇关于如何在javascript中更改当前URL?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆