如何判断用户是否在index.html 上?
我使用 document.URL 来检测用户是否在 index.html 上:
if(document.URL.indexOf("index") >-1) return true;
但是如果用户输入“mydomain.com”或“mydomain.com/”,则测试将返回 false。
我可以尝试:
if(document.URL ==="http://myDomain.com") return true;
但我想在不同的域上使用此代码。有什么建议吗?
I use document.URL to detect if a user is on index.html:
if(document.URL.indexOf("index") >-1) return true;
But if the user types "mydomain.com" or "mydomain.com/" then the test returns false.
I could try:
if(document.URL ==="http://myDomain.com") return true;
But I want to use this code on different domains. Any suggestions?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
URL 的排列有很多,可能意味着用户位于
index.html
上。相反,您不能在该文件中放置 var:只需检查
on_index
是否未定义且为 true。这将是 100% 准确的。There are so many permutations of URL that could mean that a user is on
index.html
. Instead could you not put a var within that file:Just check if
on_index
is not undefined and is true. That'll be accurate 100% of the time.javascript Location 对象 有许多有用的属性,特别是,您可以检查
位置.路径名
。基本上,如果路径名是 1) 为空 2) 等于斜杠
/
3) 以index
或/ 开头,则您位于“index”页面索引
。有关前导斜杠问题的讨论,请参阅 Javascript .pathname IE quirk?。
javascript Location object has many useful properties, in particular, you can examine
location.pathname
.Basically, you're on the "index" page if the pathname is 1) empty 2) is equal to a slash
/
3) starts withindex
or/index
.See Javascript .pathname IE quirk? for the discussion of leading slash issues.
文件和 URL 之间没有直接链接。此外,
index.html
不需要位于站点的根目录中,默认页面也不需要是index.html
。如果您想要一个通用的解决方案,那么您可能不走运。如果您想要针对您的特定情况的解决方案,您可以只提供页面本身的信息,例如定义 ID 或类名:
...或 JavaScript 变量:
如果您想要的只是对当前位置进行一些简单的字符串操作,获取
window.location
对象的pathname
属性:There isn't a direct link between files and URLs. Additionally,
index.html
does not need to be in the site's root and the default page does not need to beindex.html
.If you want a generic solution, you're probably out of luck. If you want a solution for your particular case, you can just provide that info from the page itself, e.g. defining an ID or class name:
... or a JavaScript variable:
If all you want is some simple string manipulation with current location, grab the
pathname
property of thewindow.location
object:您可以使用
如果您有权访问实际页面而不仅仅是脚本,那么您应该遵循@Ben Everard的建议。
只要确保在你的脚本之前包含他建议的片段即可。
You could use
If you have access to the actual page and not just the script then you should follow @Ben Everard's advice.
Just make sure you include the snippet he proposes before your script..