jquery,tabs,激活li上的活动类

时间:2011-03-20 02:13:43

标签: jquery jquery-ui-tabs

<script type="text/javascript"> 

$(document).ready(function() {  

    //Default Action  
    $(".tab_content").hide(); //Hide all content  
    $("ul.tabs li: #tab2").addClass("active").show(); //Activate first tab  
    $(".tab_content:#tab2").show(); //Show first tab content  
    //On Click Event  
    $("ul.tabs li").click(function() {  
        $("ul.tabs li").removeClass("active"); //Remove any "active" class  
        $(this).addClass("active"); //Add "active" class to selected tab  
        $(".tab_content").hide(); //Hide all tab content  
        var activeTab = $(this).find("a").attr("href"); //Find the rel attribute   value to identify the active tab + content  
        $(activeTab).show(); //Fade in the active content  
        return false;  
    });  

});  
</script>  

我一直在尝试这样做,目前当我打开页面时,选项卡的第二个div被选中但该行未突出显示。任何建议将不胜感激。 感谢

1 个答案:

答案 0 :(得分:0)

首先,看起来你有2个DOM节点具有相同的id属性 - “tab2” - 你不应该这样做。 ID应该是唯一的,因此很可能并非所有浏览器都能找到第二个(如果它们是单独的节点)。我很确定这基本上就是你正在做的事情:

$("#tab2").addClass("active").show(); //Activate first tab  
$("#tab2").show(); //Show first tab content 

(除非jQuery实际查看每个节点的id属性,而不是简单地在幕后使用document.getElementById,我非常怀疑。

如果你想识别某种类或选择器后面的节点,我建议改用标记来改为使用类

<tag class="tab2">
<!-- I don't know which kind of tag #tab2 was supposed to point at -->

并使用稍微不同的选择器来查找它,例如

$('ul.tabs .tab2')

其次,您在该标签中获得了href标记的属性(<a>属性),而不是<a>标记本身(因此$(this).find("a").attr("href")是返回String,可能不是您想要的,因为$.show需要DOM节点,选择器(作为String)或jQuery集。所以我改变了这个:

var activeTab = $(this).find("a").attr("href");
$(activeTab).show(); //Fade in the active content  

类似于:

var activeTab = $(this).find("a");
$(activeTab).show();  // might want to wrap this with if (activeTab.length > 0)
                      // but I can't remember what happens if you try to .show()
                      // something that isn't there

如果您尝试在有效标签中显示<a>标签。

http://api.jquery.com/show/
http://css-tricks.com/the-difference-between-id-and-class/

相关问题