如果用户访问我网站的根网址,我想运行js脚本。我正在使用此代码:
<script type="text/javascript">
if(location.pathname == "/") {
window.open ('#107','_self',false);
}
</script>
但是http://example.com/?foo=bar#hash也会运行脚本,因为路径名不包括查询字符串和位置哈希值。
目前的行为如下:
http://example/ Root
/?querystring Root
/#hash Root
/page Not root
我希望它表现得像这样:
http://example/ Root
/?querystring Not root
/#hash Not root
/page Not root
有什么建议吗? 感谢。
答案 0 :(得分:4)
使用window.location.href
代替
答案 1 :(得分:2)
您可以连接路径名,location.search和location.hash。
var fullPath = location.pathname + location.search + location.hash;
if(fullPath == "/") { /* whatever */ }
答案 2 :(得分:2)
您可以测试所有三个组件:
<script type="text/javascript">
if(location.pathname == "/" &&
location.hash.length <= 1 &&
location.search.length <= 1) {
window.open ('#107','_self',false);
}
</script>