【发布时间】: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/
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
}
【讨论】: