2011-11-07 211 views
0

我做這個代碼來顯示和隱藏p標籤取決於鏈接點擊,但如果我有100 p和鏈接我希望有一個更簡單的方法,使其動態jQuery的顯示和隱藏

<div class="example2"> 
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Fusce facilisis sagittis lectus. Curabitur quam arcu, adipiscing quis pretium in, pharetra eget dolor.</p> 
</div> 
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js" type="text/javascript"></script> 
<script type="text/javascript"> 
    $(document).ready(function() { 
     $('.example2').hide().before('<a href="#" id="toggle-example2" class="button">Open/Close</a>'); 
     $('a#toggle-example2').click(function() { 
      $('.example2').slideToggle(1000); 
      return false; 
     }); 
    }); 
</script> 




<div class="example3"> 
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Fusce facilisis sagittis lectus. Curabitur quam arcu, adipiscing quis pretium in, pharetra eget dolor.</p> 
</div> 
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js" type="text/javascript"></script> 
<script type="text/javascript"> 
    $(document).ready(function() { 
     $('.example3').hide().before('<a href="#" id="toggle-example3" class="button">Open/Close</a>'); 
     $('a#toggle-example3').click(function() { 
      $('.example3').slideToggle(1000); 
      return false; 
     }); 
    }); 
+1

您還應該修復問題標題來描述問題。 –

回答

1

您可以通過next()輕鬆遍歷下一個元素並將其切換。

<a href="#" class="button">Open/Close</a>  
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Fusce facilisis sagittis lectus. Curabitur quam arcu, adipiscing quis pretium in, pharetra eget dolor.</p> 

<a href="#" class="button">Open/Close</a> 
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Fusce facilisis sagittis lectus. Curabitur quam arcu, adipiscing quis pretium in, pharetra eget dolor.</p> 

<a href="#" class="button">Open/Close</a>  
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Fusce facilisis sagittis lectus. Curabitur quam arcu, adipiscing quis pretium in, pharetra eget dolor.</p> 


<script type="text/javascript"> 
$(function() { 
    $("a.button").click(function(e) { 
     $(this).next().slideToggle(1000); 
     e.preventDefault(); // way better than 'return false;' 
    }); 
}); 
</script>