用于基于 window.location.href 的条件 URL 附加或重定向的 Javascript [英] Javascript for conditional URL append or redirect based on window.location.href

查看:31
本文介绍了用于基于 window.location.href 的条件 URL 附加或重定向的 Javascript的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试制作一个书签,当点击它时将检查当前选项卡/窗口的 URL 以查看它是否包含char1"和/或char2"(给定的字符).如果两个字符都存在,则重定向到另一个 URL,对于其他两个字符,它将分别附加当前 URL.

I am trying to make a bookmarklet that when clicked will check the URL of the current tab/window to see if it contains 'char1' and/or 'char2' (a given character). If both chars are present it redirects to another URL, for the other two it will append the current URL respectively.

我相信一定有比以下更优雅的方式来说明这一点(到目前为止,它对我来说非常有效),但我对 Javascript 了解不多.我的(笨拙且重复的)工作代码(抱歉):

I believe there must be a more elegant way of stating this than the following (which has so far worked perfectly for me) but I don't have great knowledge of Javascript. My (unwieldy & repetitive) working code (apologies):

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');
}

完全符合我的需要,但是……至少可以说不是很优雅.

Does exactly what I need it to but, well... not very graceful to say the least.

有没有更简单的方法可以做到这一点,也许是使用 var 或伪对象?或者更好的代码?

Is there a simpler way to do this, perhaps with vars or a pseudo-object? Or better code?

推荐答案

dthorpe 建议的(排序)重构:

A (sort-of) refactoring of dthorpe's suggestion:

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 赋值是一样的,你是用加法赋值 +=无论如何方法:

Calling assign is the same as assigning a value to window.location, you were doing both with the addition assignment += operator in the method anyway:

window.location.assign(window.location.href+='append2')

这实际上会在调用assign方法之前将append2"分配到window.location.href的末尾,使其变得多余.

This would actually assign "append2" to the end of window.location.href before calling the assign method, making it redundant.

您还可以通过将 window.location 设置为 var 来减少 DOM 查找.

You could also reduce DOM lookups by setting window.location to a var.

这篇关于用于基于 window.location.href 的条件 URL 附加或重定向的 Javascript的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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