Chr*_*thy 3 javascript url document detection
我使用document.URL来检测用户是否在index.html上:
if(document.URL.indexOf("index") >-1) return true;
Run Code Online (Sandbox Code Playgroud)
但是,如果用户键入"mydomain.com"或"mydomain.com/",则测试返回false.
我可以尝试:
if(document.URL ==="http://myDomain.com") return true;
Run Code Online (Sandbox Code Playgroud)
但我想在不同的域上使用此代码.有什么建议?
Ben*_*ard 10
有如此多的URL排列可能意味着用户已经开启index.html.相反,您不能将var放在该文件中:
<script type="text/javascript">
on_index = true;
</script>
Run Code Online (Sandbox Code Playgroud)
只检查是否on_index未定义且为真.这在100%的时间内都是准确的.
javascript Location对象有许多有用的属性,特别是你可以检查location.pathname.
基本上,如果路径名是1),那么你在"索引"页面上是空的2)等于斜线/3)以index或开头/index.
var p = window.location.pathname;
if (p.length === 0 || p === "/" || p.match(/^\/?index/))
alert ("on the index page!")
Run Code Online (Sandbox Code Playgroud)
请参阅Javascript .pathname IE quirk?讨论领先的斜线问题.
| 归档时间: |
|
| 查看次数: |
4169 次 |
| 最近记录: |