0

HTML

<div class="page-content">
    <div class="something">
      <img class="image" src="something alt="something">
    </div>
    <div class="another-div-in-there"></div>
    <div class="gallery">
      //stuff in there
    </div>

    <div class="something">
      <img class="image" src="something alt="something">
    </div>
    <div class="another-div-in-there"></div>
    <div class="another-div-in-there"></div>
    <div class="gallery">
      //stuff in there
    </div>

    <div class="something">
      <img class="image" src="something alt="something">
    </div>
    <div class="another-div-in-there"></div>
    <div class="gallery">
      //stuff in there
    </div>
</div>

jQuery

$(".page-content .image").each(function(i) {
    //$(this).closest('.gallery') ??
});

如何.gallery为每个`.image`找到/选择“下一个”或“以下”

因此,当运行each()循环时,我想要第一个图像的第一个画廊。当运行第二个时,.image我想在 dom-tree 中找到.gallery第二个“下面”的那个。.image

知道怎么做吗?

4

3 回答 3

1

一种可能的解决方案:

$(".page-content .image").each(function() {
    $(this).parent().next(".gallery");
});

这里使用类名(如果存在)parent()上升<div class="something">next(".gallery")获取下一个兄弟元素。"gallery"


对于更新的问题,您可以使用.nextUntil()方法:

$(this).parent().nextUntil(".gallery").next();
于 2013-01-20T14:44:01.283 回答
1
$(".page-content .image").each(function() {
    $(this).parent().next('.gallery');
});

编辑:对于您更新的问题:

$(".page-content .image").each(function() {
    $(this).parent().nextAll('.gallery:first');
});

在此处查看示例

于 2013-01-20T14:44:18.817 回答
1

这个插件就是为此而写的。免责声明:我写的

http://techfoobar.com/jquery-next-in-dom/

$(".page-content .image").each(function() {
    $(this).nextInDOM('.gallery');
});
于 2013-01-20T14:46:58.450 回答