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
的组合。当我按下“添加”按钮时,我想获取其上方的内容div。
我正在考虑首先尝试$(this).closest('.container-fluid')
,然后导航到具有单击按钮的div上方的div。但是我不知道如何。有什么想法吗?
答案 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>