Domanda

I have the following HTML

<ul id="tabs">
    <li>1</li>
    <li>2</li>
    <li>etc...</li>
</ul> 

And the following jquery function I am using to append "buttons" for traversing "up" or "down" the list, while only "showing" the current item:

$('#tabs li').first().attr('class', 'current');

$('#tabs li').each(function(i) {
    i = i + 1;

$(this).attr('id', 'tab-' + i);

if(i !== $('#tabs li').size()) {
    $(this).append('<a class="tabPagination next floor-up" rel="tab-' + (i + 1) + '" href="/keyplate/' + (i + 1) + '">Up</a>');
    }
    if(i !== 1) {
        $(this).append('<a class="tabPagination next floor-down" rel="tab-' + (i - 1) + '" href="/keyplate/' + (i - 1) + '">Down</a>');
    }                
});            

$('#tabs li[class!="current"]').hide();

$(document).on("click", "a.tabPagination", function(){
    $('.current').removeAttr('class');
    $('#tabs li[class!="current"]').hide();    
    $('#' + $(this).attr('rel')).show(); 

});

I have another div:

<div id="tower"></div>

What I need to do is add a class to the #tower div, based on the currently selected #tab item. So for example if we are on #tab li = 2, then #tower div would get class="active_level_2". In other words, take the value of 'current' #tab list item and use that to create "active_level_#".

Thanks in advance!

È stato utile?

Soluzione

You can get the attribute rel and split it to get the last number to use for the active_level_ class. We can also pull $(this) into a variable now since its being used more than once.

jsFiddle

$(document).on("click", "a.tabPagination", function(){
    var tab = $(this);
    $('.current').removeAttr('class');
    $('#tabs li[class!="current"]').hide();    
    $('#' + tab.attr('rel')).show(); 
    for (var i = 1; i <= 6; i++)
        $('#tower').removeClass('active-level-' + i);
    $('#tower').addClass('active_level_' + tab.attr('rel').split('-')[1]);
});

tab.attr('rel').split('-')[1] will get the tab's rel attribute, split the string into two at the - character using split() and get the second part to return the number we want.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top