我使这个代码显示和隐藏p标签取决于链接点击,但如果我有100 p和链接我想要一个更容易的方式来动态
<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;
});
});
答案 0 :(得分: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>
答案 1 :(得分:0)