【发布时间】:2014-02-22 03:15:48
【问题描述】:
在我的代码中,我试图做这样的事情:
if (href = "http://hello.com")
{
whatever[0].click();
}
所以重点是,我试图让脚本仅在以特定 href 打开窗口时单击按钮。
【问题讨论】:
-
window.location对象可能对您很感兴趣。
标签: javascript dom href
在我的代码中,我试图做这样的事情:
if (href = "http://hello.com")
{
whatever[0].click();
}
所以重点是,我试图让脚本仅在以特定 href 打开窗口时单击按钮。
【问题讨论】:
window.location 对象可能对您很感兴趣。
标签: javascript dom href
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() 返回完整的 URL(即您在地址栏中看到的内容):
>>> 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 =,这是赋值,而不是比较。您需要使用== 或===(这是一个非常常见的错误,所以要当心!)
【讨论】:
if("http://hello.com" === href),如果您忘记=,则会出错。