javascript - 跨 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?"
还有这个线程提供了许多连接和推断字符串的方法,但是没有处理这个特定问题的方法。
解决方案
你应该只是使用pathname
window.location.pathname.split("/").pop()
推荐阅读
- sql - SQL Server 2019 存储过程中的 XML 节点需要 where 子句
- r - 如何在 rgl (R) 中绘制带有图例的 3D
- javascript - 为映射列表中的每个项目呈现承诺值
- amazon-web-services - 亚马逊 ses 妥协了?
- javascript - 可以将动态 html 表用作源数据吗?
- javascript - React JS:为什么 useLocation 返回未定义?
- android - 具有 BT 集成的移动应用程序的框架/工具决策
- c - C 中未初始化变量的行为
- python - 使用 python 或 c 为 android 和 iOS 创建一个 API
- python - 无法在 python 中同时创建 2 个谷歌云语音流。进程以退出代码 139 结束(被信号 11 中断:SIGSEGV)