Javascript prevAll()无法在更复杂的DOM中工作
我试图在单击按钮后选择DOM中更高的一个兄弟。我只想找到最接近的兄弟(在生产中,按钮之间有更多的HTML,因此更需要以这种方式拆分)。我使用的是Javascript prevAll()无法在更复杂的DOM中工作,javascript,jquery,html,Javascript,Jquery,Html,我试图在单击按钮后选择DOM中更高的一个兄弟。我只想找到最接近的兄弟(在生产中,按钮之间有更多的HTML,因此更需要以这种方式拆分)。我使用的是prevAll(selector:first),当我使用一个非常简单的版本()时,它似乎工作正常。但当我以更接近实际环境的方式进行操作时,prevAll()似乎找不到同级元素div.googleMapsContainer: 这是我的HTML: <div style="display: none;" class="googleMapsContai
prevAll(selector:first)
,当我使用一个非常简单的版本()时,它似乎工作正常。但当我以更接近实际环境的方式进行操作时,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>
控制台显示
closeThing
什么都不是,因为preval没有成功。这里有一个用于演示的JSFIDLE:这个对我有用,我刚刚修改了你的小提琴
我选择了同一范围内的父div,然后使用您的prevAll()
调用来精确选择。当您在实际项目中尝试这一点时会发生什么
看看:
$(document).on('click','gmapInit',function(){
var closeThing=$(this).parents(“div.tableProcessingToolBarContainer”).preval(“div.googleMapsContainer:first”);
closeThing.attr(“style”和“);
});代码>
单击后,此文本应可见
在谷歌地图中查看数据
单击后,此文本应可见
在谷歌地图中查看数据
获取匹配元素集中每个元素前面的所有同级,可选地通过选择器进行筛选parent()
和closest()
向上<代码>查找()
,子项()
向下。对,我正试图把目标对准兄弟姐妹。是div.googleMapsContainer
不是按钮的同级。gmapInit
?同级。任何不在该级别上的元素,不在父元素内的元素,都不是兄弟元素。gmapInit是其div的唯一子元素。它没有兄弟元素。啊,好的,这很有意义,谢谢。我想下面的评论员已经详细介绍了如何正确地遍历它。这就完成了,谢谢!我对DOM遍历感到困惑。
$(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", "");
});