我有4个块,我正在运行each
函数来切换活动类,但我似乎无法弄清楚如何定位特定的块我点击它只会删除{{1} } class on all elements。
这是我目前的代码
active
<div class="col-md-3">
<div class="dashboard__block">
<div class="dashboard__title">
<b>Number Of Orders</b>
| Total: 1000
</div>
<div class="dashboard__date">
<a class="black-link previous">Yesterday</a>
<a class="black-link current active">Today</a>
</div>
<div class="dashboard__data">
200
</div>
</div>
</div>
<div class="col-md-3">
<div class="dashboard__block">
<div class="dashboard__title">
<b>Number Of Orders</b>
| Total: 1000
</div>
<div class="dashboard__date">
<a class="black-link previous">Yesterday</a>
<a class="black-link current active">Today</a>
</div>
<div class="dashboard__data">
200
</div>
</div>
</div>
<div class="col-md-3">
<div class="dashboard__block">
<div class="dashboard__title">
<b>Number Of Orders</b>
| Total: 1000
</div>
<div class="dashboard__date">
<a class="black-link previous">Yesterday</a>
<a class="black-link current active">Today</a>
</div>
<div class="dashboard__data">
200
</div>
</div>
</div>
<div class="col-md-3">
<div class="dashboard__block">
<div class="dashboard__title">
<b>Number Of Orders</b>
| Total: 1000
</div>
<div class="dashboard__date">
<a class="black-link previous">Yesterday</a>
<a class="black-link current active">Today</a>
</div>
<div class="dashboard__data">
200
</div>
</div>
</div>
答案 0 :(得分:2)
您需要在父元素上下文中使用removeClass()
,这可以使用.closest()
/ .parents()
$('.dashboard__block').on('click', 'a', function () {
//Target dashboard__block then target anchors
$(this).closest('.dashboard__block').find("a").removeClass("active");
// add class to the one we clicked
$(this).addClass("active");
});
此外,您不需要.each()
绑定事件处理程序
答案 1 :(得分:0)
循环是你的问题。
删除循环并捕获onclick事件。
因此:
$(document).on("click", ".dashboard_block a", function() {
(".dashboard_block a").removeClass("active"):
$(this).addClass("active")
});
也可以做
$(".dashboard_block a:not(this)").removeClass("active")
如果被点击的元素已经有一个活动类,则在onclick事件中
答案 2 :(得分:0)
父亲比最近的人要快,但只选择一个
$('.dashboard__block').each(function(i, obj) {
$(this).find("a").click(function() {
// remove classes from all
$(this).parent("div").find("a").removeClass("active");
// add class to the one we clicked
$(this).addClass("active");
});
});
https://jsfiddle.net/Qh0stM4N/rss9ercz/
答案 3 :(得分:0)
您可以使用<a>
访问同级siblings('a')
元素,然后点击addClass('active')
上的<a>
:
$('.dashboard__block').on('click', 'a', function(e) {
$(this).siblings('a').removeClass('active').end().addClass('active');
});
请参阅Fiddle