jQuery-在父div的朋友div

时间:2018-07-13 19:28:24

标签: javascript jquery html

HTML

<div class="container-fluid">
  <div class="input-page">...</div>
  <!-- field 1 -->
  <div class="col-md-12 col-sm-12 col-xs-12 no-padding">...</div>
  <div class="col-md-12 col-sm-12 col-xs-12 no-padding">...</div>
  <!-- field 2 -->
  <div class="col-md-12 col-sm-12 col-xs-12 no-padding">...</div>
  <div class="col-md-12 col-sm-12 col-xs-12 no-padding">...</div>
  <!-- field 3 -->
  <div class="col-md-12 col-sm-12 col-xs-12 no-padding"> <!-- I want to grab this block -->
    <div class="x_panel">
      <div class="x_content">
        <form class="data-table">
          <div class="row">...</div>
          <div class="row">...</div>
  <div class="col-md-12 col-sm-12 col-xs-12 no-padding">
    <div class="btn-group">
      <button>Add</button> <!-- when I click this button -->
      <button>Other</button>
    </div>
  </div>
</div>

以上代码是简化版本,但实际代码如下所示: enter image description here

每个“ field”是内容div和按钮div的组合。当我按下“添加”按钮时,我想获取其上方的内容div。

我正在考虑首先尝试$(this).closest('.container-fluid'),然后导航到具有单击按钮的div上方的div。但是我不知道如何。有什么想法吗?

1 个答案:

答案 0 :(得分:2)

一种简单的方法是使用prev

来获取父母/父母的最接近的兄弟姐妹。

$("#AddButton").click(function() {
  var blockToGrab = $(this).parent().parent().prev();  
  // do stuff with block
  console.log("I found: " + blockToGrab.html());
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container-fluid">
  <div class="input-page">...</div>
  <!-- field 1 -->
  <div class="col-md-12 col-sm-12 col-xs-12 no-padding">...</div>
  <div class="col-md-12 col-sm-12 col-xs-12 no-padding">...</div>
  <!-- field 2 -->
  <div class="col-md-12 col-sm-12 col-xs-12 no-padding">...</div>
  <div class="col-md-12 col-sm-12 col-xs-12 no-padding">...</div>
  <!-- field 3 -->
  <div class="col-md-12 col-sm-12 col-xs-12 no-padding"> <!-- I want to grab this block -->
    <div class="x_panel">
      <div class="x_content">
        <form class="data-table">
          <div class="row">...</div>
          <div class="row">...</div>
        </form>
      </div>
    </div>
  </div>
  <div class="col-md-12 col-sm-12 col-xs-12 no-padding">
    <div class="btn-group">
      <button id="AddButton">Add</button> <!-- when I click this button -->
      <button>Other</button>
    </div>
  </div>
</div>