JavaScript进行有条件的URL追加或重定向根据window.location.href [英] Javascript for conditional URL append or redirect based on window.location.href

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

问题描述

我试图做一个书签的点击会检查当前标签/窗口的URL时,看它是否包含'CHAR1和/或CHAR2(定字符)。如果这两个字符是present它重定向到另一个网址,另外两个将分别追加当前的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的渊博知识的更优雅的方式。我的(笨拙&安培;重复)工作code(道歉):

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.

与增值经销商或伪对象有没有更简单的方式来做到这一点,也许?或者更好code?

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;

调用分配是一样的,以 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')

这实际上将调用分配方法之前将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.

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

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