在window.location.href上执行以下代码

jQuery on window.location.href execute this code

本文关键字:代码 执行 window location href      更新时间:2023-09-26

我需要从home.html转到services.html,类.services_profile是一个子菜单,需要转到services.html并使.services_profile_tab激活

$(".services_profile").click(function(e){
    $('.nav-tabs li a.tab-profile').attr("aria-expanded","true").parent().siblings().removeClass('active');
    $('.nav-tabs li a.tab-profile').parent().addClass('active');
    $('.tab-content').children().removeClass('in active');
    $('.tab-content .profile').addClass('in active');
    setTimeout(function() {
      window.location.href = 'services.html';
    },1000);
    // This does not work
    if (window.location.pathName.indexOf('services') >= 0) {
      $('services_profile_tab').addclass('active');
    }
});

路径名必须小写,如

if (window.location.pathName.indexOf('services') >= 0) {

中,在services_profile_tab之前你还缺少一个点.
$('services_profile_tab').addclass('active');

您需要将选项卡引用传递到服务页面。要么在url中,要么您可以使用window.localStorage来设置特定选项卡,以便在导航到特定页面时变得活跃,就像这样,在url中传递一个带有哈希值的ref:

$(".services_profile").click(function(e){
    $('.nav-tabs li a.tab-profile').attr("aria-expanded","true")
                                   .parent().siblings().removeClass('active');
    $('.nav-tabs li a.tab-profile').parent().addClass('active');
    $('.tab-content').children().removeClass('in active');
    $('.tab-content .profile').addClass('in active');
    setTimeout(function() {
      window.location.href = 'services.html#services_profile_tab';// pass the tab reference
    },1000);
});

现在在服务页面的doc ready块中:

$(function(){
  if (window.location.indexOf('services') >= 0) {
      var tab = window.location.hash.substr(1);
      $('.'+tab).addclass('active');
   }
});

动态传递选项卡引用的方法,如:

window.location.href = this.className.split('_')[0]'.html#'+this.className+'_tab';
// so it results in
// services.html#services_profile_tab => when "services_profile" clicked

这里的this.className是被点击来导航的元素