【问题标题】:When element clicked, find closest element relative to this element with another class and toggle it单击元素时,使用另一个类找到相对于该元素最近的元素并切换它
【发布时间】:2015-07-09 22:47:49
【问题描述】:

我在这里遗漏了一些东西。当单击类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>

【问题讨论】:

标签: javascript jquery


【解决方案1】:

类似这样的:

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

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

【讨论】:

  • 您的解决方案立即适用于这种情况。但我试图将其应用于:我想获得具有 two 类的下一个元素,该类相对于我单击的元素的位置。当我应用您的答案时,它总是返回类为two 的第一个元素,而忽略我单击的元素的位置。这有意义吗?
  • @Neil “位置”是指代码中的位置还是屏幕上的实际位置?
  • 下一个&lt;tr&gt;&lt;/tr&gt; 元素与我单击的元素相关,其类为two。我不确定您所说的代码或屏幕位置是什么意思。我认为screen,因为我使用bootstrap进行响应式设计,所以screen可能会改变。
  • @Neil 我明白了。这可能就是你想要的,demo
【解决方案2】:

我想你可能想要.next()。它根据 DOM 中的位置找到 DOM 中的下一个兄弟。

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

或者这个:get the next element with a specific class after a specific element

编辑

Here 是一个可行的解决方案:

$('.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;
        }
    }
}

【讨论】:

  • 这是一种可怕的测试类的方式,如果没有下一个具有此类的兄弟,那么您的代码将失败,因为null 没有.toggle 属性...跨度>
  • 我明白你的意思。我需要抓住那个条件。我在 click 方法中添加了一个 if then。
  • 顺便说一句,为什么这是一种“可怕”的测试课程方式。对我来说是一个教育时刻......
  • 假设元素有两个类two item,那么您的代码将静默失败。您可能想在 jQuery 中使用 .hasClass
  • 这很有意义。我会再次编辑答案。
猜你喜欢
  • 1970-01-01
  • 2016-03-25
  • 2013-03-25
  • 2014-01-04
  • 1970-01-01
  • 2019-06-07
  • 2017-05-13
  • 2015-10-03
  • 1970-01-01
相关资源
最近更新 更多