【问题标题】:If Current URL is Home Do Something如果当前 URL 是 Home 做某事
【发布时间】:2014-11-19 07:39:54
【问题描述】:

所以我有一个 JS 脚本(使用 Jquery 运行),我想根据当前页面做各种事情。

所以我有这个:

var current_url = location.pathname;

在网站主页(即 mysite.com)上,current_url 记录为“/”。

但由于某种原因,我无法得到这个 if 语句来评估......

if (current_url == '/') {
    $('header').append(autoflowside_content);
    console.log('Home!');
}

我错过了什么吗??

谢谢!

【问题讨论】:

  • 如果达到块,这是什么时候?你的 dom 就绪函数中有它吗?
  • 啊哈!它在 DOM 就绪功能中,但出现了一个恶性循环。因为 if 函数没有插入相关的代码(autoflowside_content),所以它在 DOM 就绪函数下方破坏了一行 JS,因此没有到达 if 语句。谢谢你让我检查!

标签: javascript jquery url if-statement pathname


【解决方案1】:

var current_url = location.pathname,

location.path names 在您的主机名之后返回您的路径,即在您的情况下是 mysite.com 之后。但是你的主机名后面没有段,所以你什么也找不到。

请在下面给出的 window.location 中找到一些可用的属性,然后根据您的要求选择相应的属性。 window.location 包含

         origin: "http://stackoverflow.com", 
         hash: "",
         host: "stackoverflow.com",
         hostname: "stackoverflow.com",
         href: "http://stackoverflow.com/questions/26023213/if-current-url-is-something",
         origin: "http://stackoverflow.com"
         pathname: "/questions/26023213/if-current-url-is-home-do-something",
         port: "",
         protocol: "http:",

}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-01-26
    • 1970-01-01
    • 2015-09-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多