重写一个Javascript函数,该函数可以选择在IE8中工作的活动导航选项卡

Re-write a Javascript function that selects active navigation tabs to work in IE8

本文关键字:函数 IE8 工作 选项 导航 活动 选择 一个 Javascript 重写      更新时间:2023-09-26

我在最近的一个项目中继承了一些代码,该项目使用一些CSS3选择器将类添加到一些顶级选项卡导航中。由于在后端实现的方式,JS正在搜索window.location.pathname以匹配字符串,然后在另一个函数中使用该字符串在DOM中添加类名。第二个函数使用第n个子函数(x),其中x是一个循环,对应于路径名和li中适当的匹配字符串。但是,正如您所知,IE8不支持第n个子。

我本来打算在IE8中使用这种模仿第n个孩子的风格,但我不清楚如何编写函数,将其实际添加到现有代码中。

这是我引用的JS代码:

var tabName = 'Product', tabType = window.location.pathname;
    if(tabType.indexOf('Product')>-1) tabName = 'Product'; 
    else if(tabType.indexOf('Business')>-1) tabName = 'Business'; 
    else if(tabType.indexOf('Support')>-1) tabName = 'Support';
    else if(tabType.indexOf('Article')>-1) tabName = 'Article';
$('.category-tabs li').removeClass('active');
for( var tn = 1; tn < $('.category-tabs li').length+1; tn ++ ){
    if($('.category-tabs li:nth-child(' + tn + ') a').html().indexOf(tabName)>-1){
        $('.category-tabs li:nth-child(' + tn + ')').addClass('active');
    } 
}

我想添加一个使用这个循环的函数,但同时也将其设置为"li",这样我就可以使用模拟第n个孩子的li:first-child+li方法,但我真的可以在实现这一点时提供一些帮助。

谢谢!

因为您已经在使用jQuery,请考虑用它来解决问题。只需使用.eq方法即可访问列表中的特定项。例如:

var tabName = 'Product', tabType = window.location.pathname;
    if(tabType.indexOf('Product')>-1) tabName = 'Product'; 
    else if(tabType.indexOf('Business')>-1) tabName = 'Business'; 
    else if(tabType.indexOf('Support')>-1) tabName = 'Support';
    else if(tabType.indexOf('Article')>-1) tabName = 'Article';
var liTags = $('.category-tabs li');
liTags.removeClass('active');
for( var tn = 1; tn < liTags.length+1; tn ++ ){
    var li = liTags.eq(i);
    if(li.find('a').html().indexOf(tabName)>-1){
        li.addClass('active');
    } 
}

并尝试缓存jQuery选择。它只是更干净可读。