我有两个类似的HTML块(一个用于新闻,第二个用于特别优惠),它们的底部都有分页按钮,所以我试图构建一个通用函数来为每个块独立更改分页按钮状态(活动/非活动),但我失败了。这就是问题所在。我该怎么做?
以下是 JSFiddle: http://jsfiddle.net/iamsvyat/5TjKQ/
.HTML:
<div id="news-block">News Block</div>
<div class="pag-circles">
<button class="pag-circle-1 active"> </button>
<button class="pag-circle-2 inactive"> </button>
<button class="pag-circle-3 inactive"> </button>
<button class="pag-circle-4 inactive"> </button>
</div>
<div id="special-offers-block">Special Offers Block</div>
<div class="pag-circles">
<button class="pag-circle-1 active"> </button>
<button class="pag-circle-2 inactive"> </button>
<button class="pag-circle-3 inactive"> </button>
<button class="pag-circle-4 inactive"> </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;
}
j查询:
$("#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
});
使用事件委托检查此修订版 这里
$("#firstCommonAncestor").on('click', 'button',function (e) {
var t = $(this);
t.addClass('active').removeClass('inactive').siblings().removeClass('active').addClass('inactive')
});
我想这在技术上是有效的:http://jsfiddle.net/5TjKQ/8/
不过,我不得不给你pag-circles
班div
一些身份证。
您可以将attirbute选择器与^
一起使用,或者为两者提供相同的类并使用类选择器。
$('button[class^="pag-circle-"]').click(function(){
$(this).removeClass('inactive')
.addClass("active")
.siblings()
.removeClass('active')
.addClass("inactive");
});
小提琴
查看此小提琴 http://jsfiddle.net/5TjKQ/10/
您可以获取单击按钮的参考并添加/删除相关类,如下所示
$('.pag-circles button').on('click',function(){
$(this).removeClass('inactive').addClass('active');
});
此外,您还需要更新其余按钮的类。 $.每个函数都可以解决问题。查看上面给出的 js 小提琴链接以获取完整解决方案。