jquery - 为两个相似的元素独立地使用 jQuery 更改 CSS 类

标签 jquery css

我有两个相似的 HTML block (一个用于新闻,第二个用于特别优惠),它们的底部都有分页按钮,因此我尝试构建一个通用函数来独立更改分页按钮状态(事件/非事件)每个街区,但我失败了。这就是问题所在。我该怎么做?

这是 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
});

最佳答案

使用事件委托(delegate)检查此修订 HERE

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

关于jquery - 为两个相似的元素独立地使用 jQuery 更改 CSS 类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19469348/

相关文章:

javascript - 调用针对 DOM 的自定义方法时出现的问题

javascript - 在图像上使用 load() 方法时不显示警报

javascript - 允许使用 jQuery Mask 在同一字段中使用 % 符号

javascript - 固定 html,body 时滚动到元素顶部

html - Bootstrap-如何防止这两个列表不均匀?

javascript - jquery ui Accordion 单击一次展开但第二次单击不折叠

css - 如何将 Google 图标字体添加到伪 :before

width - 设置带省略号的列的宽度

css - 完全居中图像?

html - 使用 CSS 在带有填充的渐变上叠加图像