开发者

jQuery if hasClass action

开发者_开发知识库

I have made this fiddle:

http://jsfiddle.net/4CtLV/

Now, what i'm trying to do, is if a tab has selectedTab as its class, then show the corresponding div. I've set up the if statement but am unsure where to go from here,

Any help appreciated!


Have a look at this revision.

I have factored out the code to show a tab into a function showTab:

var showTab = function(id) {
    $tab = $("#" + id);
    $('.tabTrigger').removeClass('selectedTab');
    $tab.addClass('selectedTab');
    $('.tabContent').hide();
    $('#' + id.replace('tab','content')).show();
}

The rest is then very easy:

// Show the selected tab, or the first one if none is selected
var selectedId = $('.tabTrigger.selectedTab').attr('id');
showTab(selectedId || $('.tabTrigger:first').attr('id'));

// Set up the click handlers
$('.tabTrigger').click(function(){
    showTab(this.id);
});

As a general note, in all such cases you need to factor the code you want to run into a self-contained function. Once you do that, the rest comes naturally.


Try $('.tabTrigger.selectedTab') as the selector instead, and then use .show() to show them:

$('.tabTrigger.selectedTab').show();

http://jsfiddle.net/mattlunn/4CtLV/1/


Try my update: http://jsfiddle.net/4CtLV/5/

$(document).ready(function() {
    $('.tabContent:gt(0)').hide();
    $('.tabTrigger:first').addClass('selectedTab');
    var selectedTab = $('.tabTrigger.selectedTab:first');
    if (selectedTab.length == 1) {
        $('#' + selectedTab.attr('id').replace('tab', 'content')).show();
    }
    $('.tabTrigger').click(function() {
        $('.tabTrigger').removeClass('selectedTab');
        $(this).addClass('selectedTab');
        $('.tabContent').hide();
        var id = $(this).attr('id');

        id = id.replace('tab', 'content');

        $('#' + id).show();
    });
});
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜