Jquery - 对多个路径使用 top.location.pathname?



如果网址在几个不同的路径上,特别是索引和根,我正在尝试运行一个jquery函数。现在,我有

"if (top.location.pathname === '/','index.html')
{ 
function happens
}

如果我在顶部只有一个路径名,但我不知道有两个路径名的语法,它就可以工作。我也可能会做一些相反的事情,比如:

"if (!top.location.pathname === '/','index.html')
{ 
function happens
}

在网上找不到任何解释这一点的地方!我主要是自学成才的,所以如果这很简单,那就让我轻松,哈哈。

我不完全确定你的语法,用逗号分隔'/''index.html'似乎没有必要,你可以'/index.html'.

关于实际问题,这是使用逻辑OR运算符的好时机,在Javascript中,它通常用作||

举个简单的例子:

if (true || false) // happens, because one is true
if (false || false) // doesn't happen, nothing is true
if (false || false || false || false || true) // happens, because one is true

在您的情况下,我想它会是:

if (top.location.pathname === '/index.html' || top.location.pathname === '/about.html')

我只是以about.html为例,你明白了。如果这些语句中至少有一个为真,则条件将执行。


解决您的第二点,(!top.location.pathname === '/','index.html')将无法按预期工作。

为什么?

因为!否定了它附加到的变量的值。在这种情况下,您说的是!top.location.pathname,这是在说"取路径名,并否定它,并将其与/index.html进行比较。在这种情况下,这意味着条件将沿着false === '/index.html'.

你最好否定运算符本身:(!top.location.pathname !== '/index.html').

如果要确保路径名不是任何 OR 选项,可以使用逻辑 AND (&&) 运算符。

// only matches if the pathname is neither index.html or about.html
if (top.location.pathname !== '/index.html' && top.location.pathname !== '/about.html')

最新更新