gpt4 book ai didi

javascript - window.location.href 在 .html 后带有 # hash

转载 作者:行者123 更新时间:2023-11-28 18:07:49 24 4
gpt4 key购买 nike

我正在使用 window.location.href 获取插入 jquery 的 url 路径。

它工作得很好,但现在我需要找到一条不同的路径,但我不知道该怎么做。

在我需要获取此 url user.html 并插入事件类之前

这样做:

$(document).ready(function(){
var loc = window.location.href; // returns the full URL

if(/user/.test(loc)) {
$('ul.nav.nav-tabs li').addClass('active');

}
});

现在我需要得到这个:user.html#/details

如何使用下面的代码获取此网址:user.html#/details

$(document).ready(function(){
var loc = window.location.href; // returns the full URL

if(/user/.test(loc)) {
$('ul.nav.nav-tabs li').addClass('active');

}
});

最佳答案

您可以使用以下代码实现哈希检查:

$( document ).ready(
function () {
// Get the current URL
var loc = window.location.href;
// Get the hash part
var hash = window.location.hash.replace( '#', '' );

if (
// If the location contains the word user
/user/.test( loc ) &&
// and the hash string has length greater than 0
0 < hash.length &&
// and the hash contains the string /details
/\/details/.test( hash )
) {
// Do stuff related to user page
// with the details hash part
}
}
);

此外,如果您想让它变得更复杂,您可以使用以下代码:

(function( $, window, undefined ) {

// Handle the page elements related to the hash parts
var track_hash_changes = function track_hash_changes() {
// Get the current URL
var loc = window.location.href;
// Get the hash part
var hash = window.location.hash.replace( '#', '' );

if (
// If the location contains the word user
/user/.test( loc )
) {
switch( hash ) {
case '/case-1':
// Do stuff for case #1
break;
case '/case-2':
// Do stuff for case #2
break;
case '/case-X':
// Do stuff for case #X
break;
}
}
};

$( document ).ready(
function () {
// Listen for changes in the Hash part of the URL
window.addEventListener("hashchange", track_hash_changes, false);
}
);
})( jQuery, this );

其中 case-1case-2case-Xuser.html#/case-1, user.html#/case-2, user.html#/case-X

关于javascript - window.location.href 在 .html 后带有 # hash,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42245401/

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