gpt4 book ai didi

javascript - 获取 URL 中断 chrome 和 firefox

转载 作者:行者123 更新时间:2023-11-29 18:44:58 26 4
gpt4 key购买 nike

我正在尝试通过检查我所在的页面,然后根据我所在的页面添加一个类(具有 background-image 属性)来将背景图像应用于 body 元素,即 index.php,book. php, library.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?"

还有this thread 提供了多种连接和推导字符串的方法,但是没有方法来处理这个特定问题。

最佳答案

你应该只使用 pathname

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

关于javascript - 获取 URL 中断 chrome 和 firefox,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54509268/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com