我目前正在使用以下代码来定位单个页面,例如http://my-website.com/about/
if (document.location.pathname == "/about/") {
//Code goes here
}
我想知道如何对具有特定父页面的所有页面执行相同的操作,例如/about/
以下示例。
我目前正在使用以下代码来定位单个页面,例如http://my-website.com/about/
if (document.location.pathname == "/about/") {
//Code goes here
}
我想知道如何对具有特定父页面的所有页面执行相同的操作,例如/about/
以下示例。
使用 indexOf - 它将测试所有以/about/
if (document.location.pathname.indexOf("/about/") == 0) {
//Code goes here
}
if (document.location.pathname.indexOf("/about/") === 0) {
//Code goes here
}
这将检查以确保pathname
始终以该字符串开头。如果您有兴趣更具体地检查格式,则需要使用regex
.
有点挑剔,但对于将来的参考,检查起来更安全-1
:
if (document.location.pathname.indexOf('/about') > -1) {
// your Code
}