开发者

jquery, tabs, activating active class on li

开发者 https://www.devze.com 2023-02-17 18:05 出处:网络
<script type=\"text/javascript\"> $(document).ready(function() { //Default Action $(\".tab_content\").hide(); //Hide all content
<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 conten开发者_开发技巧t  
        return false;  
    });  

});  
</script>  

I Have been trying to do this, Currently When i open the page the second div of the tab is selected but the line is not highlighted. any advice would be much appreciated. thanks


Firstly, it looks like you have 2 DOM Nodes with the same id attribute - "tab2" - you shouldn't do this. IDs are meant to be unique, so it's very possible that not all browsers will find the second one (if they're separate nodes). I'm pretty sure that this is essentially what you're doing instead:

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

(unless jQuery actually looks through every single node for an id attribute rather than simply using document.getElementById behind the scenes, which I highly doubt).

If you want to identify nodes behind a class or selector of some sort, I'd recommend using a class instead, by changing the markup to

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

and use a slightly different selector to find it, like

$('ul.tabs .tab2')

Secondly, you're getting an attribute (the href attribute) of the <a> tag in that tab, rather than the <a> tag itself (so $(this).find("a").attr("href") is returning a String, probably not what you want, as $.show expects a DOM Node, Selector (as a String), or jQuery set). So I'd change this:

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

to something like:

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

If you're trying to show <a> tags in the active tab.

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

0

精彩评论

暂无评论...
验证码 换一张
取 消