【问题标题】:Is there anything like a "if (href = ...)" command?有没有类似“if (href = ...)”命令的东西?
【发布时间】:2014-02-22 03:15:48
【问题描述】:

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

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

所以重点是,我试图让脚本仅在以特定 href 打开窗口时单击按钮。

【问题讨论】:

标签: javascript dom href


【解决方案1】:

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 =,这是赋值,而不是比较。您需要使用=====(这是一个非常常见的错误,所以要当心!)

【讨论】:

  • 避免提示中讨论的问题的一种方法是使用“Yoda Coding”并编写if("http://hello.com" === href),如果您忘记=,则会出错。
  • @BenjaminGruenbaum 我知道尤达调理。但是我从没想过使用它的这一点......谢谢你的提示。
  • @BenjaminGruenbaum 是的,Yoda conditions ...我不喜欢他们,而且我已经编程了很长时间,我几乎不再犯这个错误了。恕我直言,可读性和理智的牺牲太多了。 YMMV。
猜你喜欢
  • 1970-01-01
  • 2016-06-17
  • 1970-01-01
  • 2020-03-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多