2010-10-14 61 views
0

我有這個jquery代碼添加onclick事件,以最小化和最大化圖像崩潰和擴展div與類mainBody。選擇與類「n」div與另一個類與Jquery

在我添加div類divSectionInfo之前它正在工作,它現在意味着當您單擊icon16圖像時展開,並在單擊關閉圖像時摺疊divSectionInfo。

我有問題,選擇類div main類的div與類divSectionInfo跳過div的下一個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

這afteradding帶班divSectionInfo HERE

PD股利前:對於那些誰不知道jsbins,你可以通過單擊右上角的標籤來編輯代碼,該標籤顯示將鼠標放在該角落時的情況,並說使用jsbin編輯編輯。

謝謝。

回答

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']")

1

的jQuery:

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

的作品,但是你應該有一個ID走在其他的答案中提到。基本上取決於深層次的節點(父div與同級含divmainBodydiv - 第一的,請!),但不是去.section然後找到.mainBody(參見尼克Craver的answer)。 這樣,如果(當!)標記更改時,選擇器不太容易出錯。