jQuery - 在父div的朋友div中如何获取元素?

内容来源于 Stack Overflow,并遵循CC BY-SA 3.0许可协议进行翻译与使用

  • 回答 (1)
  • 关注 (0)
  • 查看 (113)

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>

上面的代码是一个简化版本,但实际代码如下所示:

每个“ field”都是内容div和按钮的组合div。当我按下Add按钮时,我想抓住它正上方的内容div。

我正在考虑先尝试$(this).closest('.container-fluid'),然后导航到div上方的div,它上面有我点击的按钮。但我不知道怎么做。有任何想法吗?

提问于
用户回答回答于

一种粗暴的方式:

$("#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>

扫码关注云+社区

领取腾讯云代金券