gpt4 book ai didi

javascript - 如果窗口位置是 1.html,则使用 js 重定向

转载 作者:行者123 更新时间:2023-12-03 06:47:57 24 4
gpt4 key购买 nike

我正在寻找工作原理如下的js如果在 a.html 上,则

window.location="http://www.a.com/1"

否则如果在页面 b.html 上,则

window.location="http://www.a.com/2"

最佳答案

您必须首先通过 window.location.href 检查您当前的位置才能获取网址。然后使用 substr(string, begin, lenght (optional) ) 将您的网址 chop 到末尾

//Address of your website
var url="http://example.com/"

function foo(){
var path=substr(window.location.href,url.length);
switch(path){
case "a.html": window.location="http://www.example.com/1"; break;

case "b.html": window.location="http://www.example.com/2"; break;

}
}
//don't forget to call your function

但是,如果您有内部喜好,例如http://example.com/a.html#about-us,那么这将不起作用

处理方法如下

//Address of your website
var url="http://example.com/"

function foo(){
var path=substr(window.location.href,url.length).substring(0, window.location.href.indexOf('#'));
switch(path){
case "a.html": window.location="http://www.example.com/1"; break;

case "b.html": window.location="http://www.example.com/2"; break;

}
}
//don't forget to call your function

了解更多信息

substr() http://www.w3schools.com/jsref/jsref_substr.asp

关于子串 https://developer.mozilla.org/fr/docs/Web/JavaScript/Reference/Objets_globaux/String/substring

关于javascript - 如果窗口位置是 1.html,则使用 js 重定向,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37639726/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com