【问题标题】:jQuery if Location.Pathname containsjQuery 如果 Location.Pathname 包含
【发布时间】:2013-10-27 23:45:22
【问题描述】:

我目前正在使用以下代码来定位单个页面,例如 http://my-website.com/about/

    if (document.location.pathname == "/about/") {
        //Code goes here
    }

我想知道如何对所有具有特定父页面的页面执行相同的操作,例如以下示例中的/about/..

http://my-website.com/about/child-page1

http://my-website.com/about/child-page2

【问题讨论】:

    标签: jquery url pathname


    【解决方案1】:

    使用 indexOf - 它将测试所有以 /about/ 开头的路径名为真

    if (document.location.pathname.indexOf("/about/") == 0) {
        //Code goes here
    }
    

    【讨论】:

      【解决方案2】:
          if (document.location.pathname.indexOf("/about/") === 0) {
              //Code goes here
          }
      

      这将检查以确保pathname 始终以该字符串开头。如果您有兴趣更具体地检查格式,则需要使用regex

      【讨论】:

        【解决方案3】:

        有点挑剔,但为了将来的参考,检查-1会更安全:

          if (document.location.pathname.indexOf('/about') > -1) {
            // your Code
          }
        

        【讨论】:

          猜你喜欢
          • 2013-01-08
          • 1970-01-01
          • 1970-01-01
          • 2020-12-09
          • 2018-08-14
          • 2021-04-14
          • 1970-01-01
          • 2015-12-03
          • 1970-01-01
          相关资源
          最近更新 更多