How to find the closest event element

后端 未结 2 740
终归单人心
终归单人心 2021-01-29 08:56

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

相关标签:
2条回答
  • 2021-01-29 09:17

    As suggested by Rory McCrossan; your first hideBox present directly in <table> tag which is invalid; and 2nd hideBox's <td> present outside of <tr> which is also invalid. So I am using below HTML which is somewhat different from yours but I believe you want that only

    HTML:

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

    JQuery code:

    $(".hideBox-tab").click(function(){
        $(this).closest("tr").find(".hideBox").toggle();
        return false;
    }); 
    
    0 讨论(0)
  • 2021-01-29 09:40

    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>

    0 讨论(0)
提交回复
热议问题