简体   繁体   English

jQuery 如何定位兄弟姐妹的孩子?

[英]jQuery how to target children of siblings?

I'm having issues removing the active class in a certain div.我在删除某个 div 中的活动类时遇到问题。 I use two filters, but somehow if I click on one, the other filter also gets the active class removed.我使用了两个过滤器,但不知何故,如果我单击一个过滤器,另一个过滤器也会删除活动类。 How can I only target and remove the active class of the children of siblings?我怎样才能只针对和删除兄弟姐妹的孩子的活动类?

Here's my HTML:这是我的 HTML:

<ul class="filter">
<li class="option"> <a class="link active">
<li class="option"> <a class="link">
<li class="option"> <a class="link">
</ul>

<ul class="filter2">
<li class="option"> <a class="link active">
<li class="option"> <a class="link">
<li class="option"> <a class="link">
</ul>

And here's my jQuery code:这是我的 jQuery 代码:

$(document).ready(function () {
    $('.link').bind('click', function() {
        // remove the active class from all elements with active class
        $('.active').removeClass('active')
        // add active class to clicked element
        $(this).addClass('active');
    });
});

You can use $(this).closest("ul") to find th ul containing the element that was clicked, then find to find the .active elements in just that ul :您可以使用$(this).closest("ul")找到包含被点击元素的ul ,然后find找到.active元素在那个ul

$('.link').on('click', function() {
    const $this = $(this);
    $this.closest("ul").find(".active").removeClass("active");
    $this.addClass('active');
});

Side note: I changed bind to on .旁注:我将bind更改为on bind has been deprecated for years. bind已被弃用多年。

<div>
    <ul class="filter">
        <li class="option"> <a href="javascript:;" class="link active">1</a></li>
        <li class="option"> <a href="javascript:;" class="link">2</a></li>
        <li class="option"> <a href="javascript:;" class="link">3</a></li>
    </ul>
    <ul class="filter">
        <li class="option"> <a href="javascript:;" class="link active">4</a></li>
        <li class="option"> <a href="javascript:;" class="link">5</a></li>
        <li class="option"> <a href="javascript:;" class="link">6</a></li>
    </ul>
</div>
<script>
    $(function() {
        $('.filter .link').click(function(){
            $(this).addClass('active').closest('.filter').find('.link').not(this).removeClass('active');
        });
    });
</script>

check this one-liner检查这个单衬

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM