如果Location.Pathname包含jQuery

SBM*_*SBM 4 url jquery pathname

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

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

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

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

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

Aru*_*hny 15

使用indexOf - 对于以.开头的所有路径名,它将测试为true /about/

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


mar*_*ljn 5

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

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