首页 > 解决方案 > 跨 chrome 和 firefox 获取 URL 中断

问题描述

我试图通过检查我在哪个页面上将背景图像应用到正文元素,然后根据我所在的页面添加一个类(具有背景图像属性),即 index.php、book.php、库.php 等

目前,我正在使用 document.location 对象(即 document.location.href),并且我也尝试过 window.location 对象,但无济于事。

我的问题是 Firefox 返回的 URL 没有尾随哈希 (#) 或问号 (?),而 Chrome 返回带有这些尾随字符的 URL,无论所述字符后面是否有任何其他 URL。

这是我的代码:

 switch(currentFileName()) {
case "index.php": bodyBackGroundFadeIn('home');
  break;
case "library.php": bodyBackGroundFadeIn('library');
  break;
case "store_library.php": 
bodyBackGroundFadeIn('store_library');
  break;
case "book.php": bodyBackGroundFadeIn('book');
  break;
case "store_book.php": bodyBackGroundFadeIn('store_book');
  break;
  }

function currentFileName(){
var href = document.location.href;
return href.substr(href.lastIndexOf("/") + 1);
}


function bodyBackGroundFadeIn(class_name){

 $(document.body).addClass(class_name);
 $(document.body).animate({opacity: 1.0},'600');

}

有没有更好的方法来达到这个效果?我考虑过使用正则表达式来搜索“?” 或'#',但如果它不是跨浏览器,我不想搞砸这个。

我还尝试使用按位运算符来反转空哈希值,以使其在 Firefox 和 Chrome 上工作,但这也不起作用。

这是 Firefox 的输出:

>> document.location.href.substr(href.lastIndexOf("/") + 1);
"index.php" 

这是 Chrome 的输出:

>> document.location.href.substr(href.lastIndexOf("/") + 1);
"index.php?"

还有这个线程提供了许多连接和推断字符串的方法,但是没有处理这个特定问题的方法。

标签: javascripturl-rewriting

解决方案


你应该只是使用pathname

window.location.pathname.split("/").pop()

推荐阅读