2013-12-09 37 views
0

我很新jQuery的。使用toggleClass上點擊 - jQuery的

我有兩個菜單選項卡,並想獲得標籤「a」到切換(開關)類與標籤「B」後點擊。

使用.attr方法似乎並沒有工作。我也嘗試用toggleClass切換它,但仍然沒有。

// toggle between login/register 
$(".static-color").click(function() { 
    $("#login").hide(); 
    $("#register").show(); 

    $(this).attr("active-color"); 
    $(".active-color").attr("static-color"); 

}); 

// toggle between login/register 
$(".active-color").click(function() { 
    $("#login").show(); 
    $("#register").hide(); 

    $(this).attr("static-color"); 
    $(".static-color").attr("active-color"); 
}); 

http://jsfiddle.net/h3Y6G/

+0

http://jsfiddle.net/h3Y6G/6/我已經更新;切換班級;如果您可以使用ID登錄並註冊 s,那很容易。這也起作用。 $(「。active-color」)。removeClass(「active-color」)。addClass(「static-color」); $(本).removeClass( 「靜態色」)addClass( 「激活色」)。切換。 – user1769790

回答

1

你實際上與.attr是剛開應該static-color屬性不存在的價值做。

訣竅是使用.addClass.removeClass或在這種情況下.toggleClass

另一個祕訣我對你是使用事件代表團的jQuery的.on方法。這將允許更靈活的事件處理。你實際上是連接聽衆到會聽取來自其他元素來指定選擇器匹配的事件父元素,像這樣:

$("#login-register").on('click', '.static-color', function() { 
    $('.active-color, .static-color').toggleClass("active-color static-color"); 
    $("#login, #register").toggle(); 
}); 

而且,我看你有一點重複,儘量使你的代碼更可重用。 Don't Repeat Yourself

我更新了你的提琴:http://jsfiddle.net/h3Y6G/1/

0

「活性色」 不是一個屬性。

難道你的意思是切換CSS或類呢?

$(this).attr("active-color"); 

成爲

$(this).addClass('active-color').removeClass('static-color'); 

或扭轉它,只是切換類的名稱:

$(this).addClass('static-color').removeClass('active-color'); 
+0

和其他按鈕...? –

1

我的建議是使用button類作爲您選擇用於切換類,並刪除static類。你可以假設,如果你的按鈕不是「活動的」,那麼它就會是「靜態的」,你應該相應地設計它們。

試試這個:

$('.button').click(function() { 
    // remove active class from all buttons 
    $('.button').removeClass('active-color'); 
    // add it to the current clicked button 
    $(this).addClass('active-color'); 
    // get button type and deal with content accordingly 
    var button_type = $(this).text().trim(); 
    if(button_type == "Register") { 
     $("#register").show(); 
     $("#login").hide(); 
    } else if(button_type == "Log-In") { 
     $("#login").show(); 
     $("#register").hide(); 
    } 
}); 

的jsfiddle:http://jsfiddle.net/h3Y6G/2/

+1

整理這個答案:http://jsfiddle.net/h3Y6G/7/ –