单击按钮后,我试图在DOM中进一步选择单个同级。我只想查找最接近的同级对象(在生产中,按钮之间有很多HTML,因此更需要以这种方式将其拆分)。我正在使用prevAll(selector:first)
来执行此操作,当我使用非常简单的版本(here)时,它似乎可以正常工作。但是,当我以与实际环境更相似的方式进行操作时,prevAll()似乎找不到同级元素div.googleMapsContainer
:
这是我的HTML:
<div style="display: none;" class="googleMapsContainer" id="gm1">
<div class="gmap" style="max-width: 80%;
max-height: 400px;
background-color: grey;" class="map">
</div>
This Text Should be visible after click
</div>
<div class="tableProcessingToolBarContainer">
<div class="container-fluid tableProcessingTools" >
<div class="row-fluid">
<div class="appSliderContent tptSliderContent container-fluid ">
<button class="gmapInit glassyButton">View data in Google Maps</button>
</div>
</div>
</div>
</div>
<div style="display: none;" class="googleMapsContainer" id="gm2">
<div class="gmap" style="max-width: 80%;
max-height: 400px;
background-color: grey;" class="map">
</div>
This Text Should be visible after click
</div>
<br>
<div class="tableProcessingToolBarContainer">
<div class="container-fluid tableProcessingTools" >
<div class="row-fluid">
<div class="appSliderContent tptSliderContent container-fluid ">
<button class="gmapInit glassyButton">View data in Google Maps</button>
</div>
</div>
</div>
</div>
这是我的JavaScript:
$(document).on('click', '.gmapInit', function() {
console.log("here is this: ");
console.log($(this));
var closeThing = $(this).prevAll("div.googleMapsContainer:first");
console.log("here is the closest: ");
console.log(closeThing);
closeThing.attr("style", "");
});
控制台显示
closeThing
无效,因为prevAll不成功。这是一个用于演示的JsFiddle:https://jsfiddle.net/NateH06/twk9mtjg/ 最佳答案
这个正在为我工作,我刚刚修改了您的小提琴。
我选择了在相同范围内的父div,然后使用prevAll()
调用来精确选择。在实际项目中尝试此操作会发生什么?
看一看:
$(document).on('click', '.gmapInit', function() {
var closeThing = $(this).parents("div.tableProcessingToolBarContainer").prevAll("div.googleMapsContainer:first");
closeThing.attr("style", "");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div style="display: none;" class="googleMapsContainer" id="gm1">
<div class="gmap" style="max-width: 80%;
max-height: 400px;
background-color: grey;" class="map">
</div>
This Text Should be visible after click
</div>
<div class="tableProcessingToolBarContainer">
<div class="container-fluid tableProcessingTools" >
<div class="row-fluid">
<div class="appSliderContent tptSliderContent container-fluid ">
<button class="gmapInit glassyButton">View data in Google Maps</button>
</div>
</div>
</div>
</div>
<div style="display: none;" class="googleMapsContainer" id="gm2">
<div class="gmap" style="max-width: 80%;
max-height: 400px;
background-color: grey;" class="map">
</div>
This Text Should be visible after click
</div>
<br>
<div class="tableProcessingToolBarContainer">
<div class="container-fluid tableProcessingTools" >
<div class="row-fluid">
<div class="appSliderContent tptSliderContent container-fluid ">
<button class="gmapInit glassyButton">View data in Google Maps</button>
</div>
</div>
</div>
</div>