【问题标题】:Select div with class "n" after another div with another class with Jquery在另一个 div 与另一个类与 Jquery 之后选择具有类“n”的 div
【发布时间】:2010-10-14 21:41:16
【问题描述】:

我有这个 jquery 代码来添加 onclick 事件以最小化和最大化图像折叠和扩展具有类 mainBody 的 div。

在我添加带有类 divSectionInfo 的 div 之前,它可以工作,现在当您单击 icon16 图像时它会展开,并在单击关闭图像时折叠 divSectionInfo。

我在选择下一个带有 mainBody 类的 div 时遇到问题,跳过带有 divSectionInfo 类的 div。

HTML 示例

<span class="section" style="clear: both">
    <div class="top">
        <h2>
            <a href="javascript: void(0);">Heading </a>
            <img src='../Images/min.gif' style='float:right;' alt='minimize'/>
            <img src='../Images/max.gif' style='float:right;' alt='maximize'/>
            <img src="../Images/icon16.png" style="margin-right: 50px;" alt="expand divSectionInfo" />
        </h2>
    </div>
    <div class="divSectionInfo">
        <span>This is text</span>
        <span>This is text</span>
            <img src="../GlobalResources/Images/close.png" alt="collapse divSectionInfo"/>
        </div>
    <div>
    <div class="mainBody"></div>//This div is supposed to collapse and expand when minimize and maximize button are clicked.
    </div>

jQuery 代码。

  $("img[alt='maximize']").click(function (e) {
    //alert("2");
    $(this).closest("div").next("div").slideDown("fast");
    e.stopPropagation();
    return false;
});

要查看一个工作示例HERE,这是在添加具有类 divSectionInfo 的 div 之前

这是在添加带有类 divSectionInfo HERE 的 div 之后

PD:对于那些不了解 jsbins 的人,您可以通过单击右上角的标签来编辑代码,当您将鼠标放在那个角落并说使用 jsbin 进行编辑时会显示该标签。

谢谢。

【问题讨论】:

    标签: jquery html css-selectors


    【解决方案1】:

    我会在这里使用.closest().find() 是最灵活的,就像这样:

    $("img[alt='maximize']").click(function (e) {
      $(this).closest(".section").find(".mainBody").slideDown("fast");
      e.stopPropagation();
    });
    

    You can see your demo updated/working with this code here。不过,我会给你的按钮一个类,例如:

    <img class="minimize" src='http://png.findicons.com/files/icons/653/the_spherical/32/minimize.png' style='float:right;' alt='minimize'/>
    <img class="maximize" src='http://www.winnipegringette.com/images/icons/maximize.png' style='float:right;' alt='maximize'/>
    

    然后更改您的选择器以使用它,$("img.maximize") 而不是 $("img[alt='maximize']")

    【讨论】:

      【解决方案2】:

      jQuery:

      $(this).closest("div").siblings("div").find("div.mainBody:eq(0)")
      

      有效,但您可能应该使用其他答案中提到的 ID。基本上 取决于深层节点层次结构(父 div 与兄弟 div 包含 div 与类 mainBody - 其中第一个,拜托!)而是去@987654327 @ 然后找到 .mainBody(参见 Nick Craver 的 answer)。 这样,如果(何时!)标记发生变化,您的选择器就不太容易出错。

      【讨论】:

        猜你喜欢
        • 2011-07-29
        • 1970-01-01
        • 2023-04-07
        • 1970-01-01
        • 2021-08-03
        • 1970-01-01
        • 1970-01-01
        • 2022-01-22
        • 2022-12-03
        相关资源
        最近更新 更多