有什么像“if(href = ...)”命令吗?

时间:2014-02-21 18:53:40

标签: javascript dom href

在我的代码中,我试图做这样的事情:

if (href = "http://hello.com")
{
whatever[0].click();
}

所以关键是,我正在尝试让脚本仅在特定href中打开窗口时单击按钮。

1 个答案:

答案 0 :(得分:4)

window.location包含许多有趣的值:

hash ""
host "stackoverflow.com"
hostname "stackoverflow.com"
href "http://stackoverflow.com/questions/21942858/is-there-anything-like-a-if-href-command"
pathname "/questions/21942858/is-there-anything-like-a-if-href-command"
port ""
protocol "http:"
search ""

所以,在你的例子中,那将是:

if (window.location.hostname === "hello.com") {
}

或者,您知道域名后可能要做的事情是使用pathname

if (window.location.pathname === '/questions/21942858/is-there-anything-like-a-if-href-command') {
}

window.location.toString()会返回完整的网址(即您在地址栏中看到的内容):

>>> window.location.toString()
"http://stackoverflow.com/questions/21942858/is-there-anything-like-a-if-href-command/21942892?noredirect=1#comment33241527_21942892"

>>> window.location === 'http://stackoverflow.com/questions/21942858/is-there-anything-like-a-if-href-command/21942892?noredirect=1#comment33241527_21942892'
true

我一直避免这种情况,因为1)当你更改协议时它会中断(http / https)2)当你在另一个域上运行脚本时中断。我建议使用pathname

另见MDN

奖金提示

你的例子是这样的:

if (href = "http://hello.com")

您使用 ONE =,这是分配,而不是比较。您需要使用=====(这是一个非常常见的错误,因此请注意它!)

相关问题