2012-01-25 18 views
0

我有一個簡單的隱藏顯示jQuery的腳本,我從一個示例網站抓住。我試圖遍歷使用$(this)。瞄準我想隱藏/顯示的div。第一次失敗後,我一直能夠做這項工作。我已經修改了代碼,所以我有幾個失敗的例子來幫助看看我正在嘗試做什麼。這是代碼。jQuery的隱藏顯示或切換div循環命名需要解決方案

<script type="text/javascript"> 
//$(document).ready(function(){ 
// $("#hide").click(function(){ 
// $(this).('#hideShowParent > #hideShow').hide(); 
// }); 
// $("#show").click(function(){ 
// $(this).('#hideShowParent > #hideShow').show(); 
// }); 
//}); 
$(document).ready(function(){ 
$("#hide").click(function(){ 
    $(this).find().parent("#hideShowParent").sibling("#hideShow").hide(); 
}); 
$("#show").click(function(){ 
    $(this).find().parent("#hideShowParent").sibling("#hideShow").hide(); 
}); 
}); 
</script> 

現在我正在循環可能有一個或兩個或更多的東西。我想爲我的jQuery的目標點擊的按鈕的父母,找到兄弟在下面的最接近的div稱爲隱藏顯示和隱藏或顯示(可以事先使用撥動了。

<div id="hideShowParent"> 
<ul> 
<li> 
    <button id="show">Show</button> 
    - <button id="hide">Hide</button> 
    <b>Medium</b> 
     <div id="hideShow"> 

       <table> 
        <tr> 
         <td><hr /></td> 
        </tr>    
        <tr><td height="15px">somethingn textual</td></tr> 
        <tr> 
         <td><hr /></td> 
        </tr> 
       </table> 

     </div> 
</li> 
</ul> 
</div> 
<div id="hideShowParent"> 
<ul> 
<li> 
    <button id="show">Show</button> 
    - <button id="hide">Hide</button> 
    <b>Medium</b> 
     <div id="hideShow"> 

       <table> 
        <tr> 
         <td><hr /></td> 
        </tr>    
        <tr><td height="15px">somethingn textual</td></tr> 
        <tr> 
         <td><hr /></td> 
        </tr> 
       </table> 

     </div> 
</li> 
</ul> 
</div> 

感謝您的幫助。我希望這一切有意義

+0

切換會工作 - 但與2個按鈕....你可以使用相同的按鈕,並使用'切換()' – ManseUK

回答

1

首先應該以這種方式使用id屬性 - 的ID應該是唯一的,所以我會用class屬性,它可以是相同的多個DOM元素替換它們:。

<div class="hideShowParent"> 
<ul> 
<li> 
    <button class="show">Show</button> 
    - <button class="hide">Hide</button> 
    <b>Medium</b> 
     <div class="hideShow"> 

       <table> 
        <tr> 
         <td><hr /></td> 
        </tr>    
        <tr><td height="15px">somethingn textual</td></tr> 
        <tr> 
         <td><hr /></td> 
        </tr> 
       </table> 

     </div> 
</li> 
</ul> 
</div> 
<div class="hideShowParent"> 
<ul> 
<li> 
    <button class="show">Show</button> 
    - <button class="hide">Hide</button> 
    <b>Medium</b> 
     <div class="hideShow"> 

       <table> 
        <tr> 
         <td><hr /></td> 
        </tr>    
        <tr><td height="15px">somethingn textual</td></tr> 
        <tr> 
         <td><hr /></td> 
        </tr> 
       </table> 

     </div> 
</li> 
</ul> 
</div> 

下面的代碼將工作,那麼:

$(document).ready(function() { 
    $(".hide").click(function() { 
     $(this).siblings(".hideShow").hide(); 
    }); 
    $(".show").click(function() { 
     $(this).siblings(".hideShow").show(); 
    }); 
}); 

工作例如:http://jsfiddle.net/MztAm/