简体   繁体   English

单击元素时,使用另一个类查找相对于该元素的最近元素,并进行切换

[英]When element clicked, find closest element relative to this element with another class and toggle it

I am missing something here. 我在这里错过了一些东西。 When the row with the class one is clicked, I want to find only the closest row with the class two and then toggle (show/hide) it. 当与类行one被点击时,我想用类只找到最接近的行two ,然后切换(显示/隐藏)它。

 $(".one").on('click', function() { $(this).find('.two').toggle(); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <table> <tr class="one"> <td> Hello </td> </tr> <tr> <td> world </td> </tr> <tr class="two"> <td> Foo </td> </tr> <tr class="two"> <td> Bar </td> </tr> </table> 

Something like this: 像这样:

$(".one").on('click', function() {
    $(this).nextAll('.two:first').toggle(); 
});

http://jsfiddle.net/DerekL/5ossufmj/ http://jsfiddle.net/DerekL/5ossufmj/

I think you might want .next() . 我认为您可能需要.next() It finds the next sibling in the DOM respecting placement in the DOM. 它在DOM中尊重DOM中的位置的情况下找到DOM中的下一个同级。

https://api.jquery.com/next/ https://api.jquery.com/next/

Or maybe this: get the next element with a specific class after a specific element 或者也许是这样: 在特定元素之后获取具有特定类的下一个元素

Edit 编辑

Here is a working solution: 是一个可行的解决方案:

$('.one').on('click', function () {
    var this_el = $(this);
    var el = findNextWithClass(this_el, "two");
    if (el != null)
    {
        el.toggle();
    }
    else
    {
        alert("null");
    }
});

function findNextWithClass(element, className) {
    var next = element.next();
    if (next.hasClass(className)) {
        return next
    } else {
        if (next != null) {
            return findNextWithClass(next, className);
        } else {
            return null;
        }
    }
}

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

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