如何找到最接近的事件元素 [英] How to find the closest event element

查看:84
本文介绍了如何找到最接近的事件元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用jQuery.我想找到最接近创建事件的元素的类.hidebox.我尝试使用parentfindclosest,但是它们都引用了我的元素所在的级别.我只是在寻找与事件元素最接近的.hidebox类.

I'm using jQuery. I want to find the closest class .hidebox to the element that created the event. I tried to use parent, find and closest but they all refer to the level my element located. I'm just looking to the closest .hidebox class I can find to my event element.

<tr>
    <td></td>
    <td>
        <a href="#" class="hideBox-tab " >show div</a>
    </td>
</tr>
<div class="hideBox" ></div>

<tr>
    <td></td>
    <td>
        <a href="#" class="hideBox-tab " >show div</a>
    </td>
</tr>
<tr>
</td>
    <div class="hideBox" ></div>
</td>
</tr>

$(".hideBox-tab").click(function(){
    $(this)
        .parent().parent()
        .find(".hideBox")
        .toggle();
    return false;
}); 

推荐答案

尽管您具有html有效性,也可以尝试这样做:

Despite of your html validity you can try do it like this:

$(".hideBox-tab").click(function(){
    $(this)
        .closest("tr")
        .next("tr")
    		.find(".hideBox")
        .toggle();
    return false;
}); 

.hideBox {
  display:none;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<table>
  <tr>
    <td>
      <a href="#" class="hideBox-tab">show div</a>
    </td>
  </tr>
  <tr>
    <td>
      <div class="hideBox">aaa</div>      
    </td>
  </tr>
  <tr>
    <td>
      <a href="#" class="hideBox-tab">show div</a>
    </td>
  </tr>
  <tr>
    <td>
      <div class="hideBox">bbb</div>      
    </td>
  </tr>
</table>

这篇关于如何找到最接近的事件元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆