2013-10-19 64 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小提琴链接以获得完整解决方案。