2013-10-19 150 views
0

我有兩個類似的HTML塊(一個用於新聞,第二個用於特殊優惠),它們在底部都有分頁按鈕,所以我嘗試構建一個通用函數來更改分頁按鈕狀態(活動/不活動)爲每個塊獨立,但我失敗了。這就是問題所在。我該怎麼做?使用jQuery獨立更改兩個類似元素的CSS類

這裏是的jsfiddle:http://jsfiddle.net/iamsvyat/5TjKQ/

HTML:

<div id="news-block">News Block</div> 
<div class="pag-circles"> 
    <button class="pag-circle-1 active">&nbsp;</button> 
    <button class="pag-circle-2 inactive">&nbsp;</button> 
    <button class="pag-circle-3 inactive">&nbsp;</button> 
    <button class="pag-circle-4 inactive">&nbsp;</button> 
</div> 
<div id="special-offers-block">Special Offers Block</div> 
<div class="pag-circles"> 
    <button class="pag-circle-1 active">&nbsp;</button> 
    <button class="pag-circle-2 inactive">&nbsp;</button> 
    <button class="pag-circle-3 inactive">&nbsp;</button> 
    <button class="pag-circle-4 inactive">&nbsp;</button> 
</div> 

CSS:

button { 
    width: 0; 
    height: 0; 
    margin: 0; 
    padding: 0; 
    border: 6px solid black; 
    border-radius: 6px; 
} 
.active { 
    border-color: red; 
} 
.inactive { 
    border-color: black; 
} 
button:focus { 
    outline: none; 
} 
button:active { 
    position: relative; 
    top: 1px; 
} 

jQuery的:使用事件德勒

$("#news-block").next(".pag-circles").children().click(function() { 
    //if the first button is clicked 
    //if the second button is clicked 
    //if the third button is clicked 
    //if the fourth button is clicked 
}); 
$("#special-offers-block").next(".pag-circles").children().click(function() { 
    //if the first button is clicked 
    //if the second button is clicked 
    //if the third button is clicked 
    //if the fourth button is clicked 
}); 
+1

將按鈕設置爲同一類是否合理? – j08691

回答

1

檢查本次修訂通貨膨脹HERE

$("#firstCommonAncestor").on('click', 'button',function (e) { 
    var t = $(this); 
    t.addClass('active').removeClass('inactive').siblings().removeClass('active').addClass('inactive') 
}); 
+0

謝謝!最明確的答案。 – svtslvskl

+0

不客氣! [Documentation](http://api.jquery.com/on/)很容易閱讀和理解,看看如果還沒有完成';)' – Stphane

1

你可以使用attirbute選擇器與^或給相同的類和使用類選擇器。

$('button[class^="pag-circle-"]').click(function(){ 
    $(this).removeClass('inactive') 
      .addClass("active") 
      .siblings() 
      .removeClass('active') 
      .addClass("inactive"); 
}); 

fiddle

1

結帳這個小提琴http://jsfiddle.net/5TjKQ/10/

,您就能獲得點擊按鈕的參考和添加/刪除相關類,如下

$('.pag-circles button').on('click',function(){ 
    $(this).removeClass('inactive').addClass('active'); 
}); 

你也將需要更新,其餘按鈕的類也是如此。 $。每個函數都可以做到這一點。檢出上面給出的js小提琴鏈接以獲得完整解決方案。