获取跨越Chrome和Firefox的URL休息

问题描述 投票:2回答:1

我想基于我是对的index.php即,book.php中,图书馆的网页上检查我在哪个页面,然后添加一个类(用background-image属性)应用的背景图像body元素.PHP等。

目前,我使用的document.location对象(即document.location.href),我也曾尝试window.location的对象无济于事。

我的问题是Firefox的返回地址没有尾随哈希(#)或问号(?),而镀铬与这些尾随字符是否存在以下称字符的任何额外的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?"

还有this线程它提供了多种方式来连接和推断的字符串,但是没有方法来处理这个具体问题。

javascript url-rewriting
1个回答
3
投票

你应该只使用pathname

window.location.pathname.split("/").pop()
© www.soinside.com 2019 - 2024. All rights reserved.