![](/img/trans.png)
[英]how the browser execute this javascript code: window.location.href=“url”
[英]Javascript for conditional URL append or redirect based on window.location.href
我正在嘗試制作一個書簽,當點擊它時將檢查當前標簽/窗口的URL,看它是否包含'char1'和/或'char2'(給定字符)。 如果兩個字符都存在,則重定向到另一個URL,對於另外兩個字符,它將分別附加當前URL。
我相信必須有一個更優雅的方式陳述這個比以下(迄今為止對我來說完美的工作)但我對Javascript沒有很好的了解。 我的(笨重的和重復的)工作代碼(道歉):
if (window.location.href.indexOf('char1') != -1 &&
window.location.href.indexOf('char2') != -1)
{
window.location="https://website.com/";
}
else if (window.location.href.indexOf('char1') != -1)
{
window.location.assign(window.location.href += 'append1');
}
else if (window.location.href.indexOf('char2') != -1)
{
window.location.assign(window.location.href += 'append2');
}
完全是我需要的,但是,好吧......至少可以說不是很優雅。
有沒有更簡單的方法來做到這一點,也許是對於vars或偽對象? 還是更好的代碼?
對dthorpe建議的一種(類型)重構:
var hasC1 = window.location.href.indexOf('char1')!=-1
var hasC2 = window.location.href.indexOf('char2')!=-1
var newLoc = hasC1
? hasC2 ? "https://website.com/" : window.location.href+'append1'
: hasC2 ? window.location.href+'append1' : '';
if (newLoc)
window.location = newLoc;
調用assign
與為window.location
分配值相同,無論如何你在方法中都使用了加法賦值+=
運算符:
window.location.assign(window.location.href+='append2')
這實際上會在調用assign方法之前將“append2”分配給window.location.href
的末尾,從而使其成為冗余。
您還可以通過將window.location
設置為var來減少DOM查找。
我能看到的唯一減少是將多余的調用索引拉入變量,然后測試變量。 但是,它不會在性能方面產生任何明顯的差異。
var hasChar1 = window.location.href.indexOf('char1') != -1;
var hasChar2 = window.location.href.indexOf('char2') != -1;
if (hasChar1)
{
if (hasChar2)
{
window.location="https://website.com/";
}
else
{
window.location.assign(window.location.href+='append1');
}
}
else if (hasChar2)
{
window.location.assign(window.location.href+='append2');
}
一種可擴展的代碼。 我瘋了嗎?
var loc = window.location.href;
var arr = [{
url: "https://website.com/",
chars: ["char1", "char2"]
}, {
url: loc + "append1",
chars: ["char1"]
}, {
url: loc + "append2",
chars: ["char2"]
}];
function containsChars(str, chars)
{
var contains = true;
for(index in chars) {
if(str.indexOf(chars[index]) == -1) {
contains = false;
break;
}
}
return contains;
}
for(index in arr) {
var item = arr[index];
if(containsChars(loc, item.chars)) {
window.location.href = item.url;
break;
}
}
var location = window.location.href
if (location.indexOf('char1')!=-1 && location.indexOf('char2')!=-1)
{window.location="https://website.com/";}
else if (location.href.indexOf('char1')!=-1) {window.location.assign(location+='append1');}
else if (location.indexOf('char2')!=-1) {window.location.assign(location+='append2');}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.