8

我目前正在使用以下代码来定位单个页面,例如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

4

3 回答 3

22

使用 indexOf - 它将测试所有以/about/

if (document.location.pathname.indexOf("/about/") == 0) {
    //Code goes here
}
于 2013-10-19T01:43:14.017 回答
4
    if (document.location.pathname.indexOf("/about/") === 0) {
        //Code goes here
    }

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

于 2013-10-19T01:43:31.970 回答
0

有点挑剔,但对于将来的参考,检查起来更安全-1

  if (document.location.pathname.indexOf('/about') > -1) {
    // your Code
  }
于 2022-01-09T16:03:44.933 回答