我目前正在使用下面的代码来针对单个页面,例如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
发布于 2013-10-19 01:43:14
使用indexOf -它将测试所有以/about/开头的路径名为true
if (document.location.pathname.indexOf("/about/") == 0) {
//Code goes here
}发布于 2013-10-19 01:43:31
if (document.location.pathname.indexOf("/about/") === 0) {
//Code goes here
}这将检查以确保pathname总是以该字符串开头。如果您有兴趣更具体地检查格式,则需要使用regex。
发布于 2022-01-09 16:03:44
有点挑剔,但是对于将来的参考资料,检查一下-1是更安全的
if (document.location.pathname.indexOf('/about') > -1) {
// your Code
}https://stackoverflow.com/questions/19461395
复制相似问题