如何为多个实例创建函数

时间:2011-03-10 11:12:58

标签: jquery

我写了一个小代码来显示hide元素及其工作正常。我该怎么做才能使它适用于多个实例。如何为多个实例创建代码

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
<style>
.heading{ font-size:18px}
.paragraph{ font-size:12px; height:0; overflow:hidden; background-color:#CCCCCC;}
.close{ color:#FF0000; font-weight:bold;}

</style>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>

</head>
<div>
    <h1 class="heading">This is Heading</h1>
    <p class="paragraph">This is paragraph. This is paragraph. This is paragraph. This is paragraph. This is paragraph. This is paragraph. This is paragraph.<br/><span class="close">Close</span> </p>
</div>
<div>
    <h1 class="heading">This is Heading</h1>
    <p class="paragraph">This is paragraph. This is paragraph. This is paragraph. This is paragraph. This is paragraph. This is paragraph. This is paragraph.<br/><span class="close">Close</span> </p>
</div>

<script>
$('h1.heading').click(function(){
$clickedElement=$(this);
$('$clickedElement.paragraph').animate({'height':'50px'},1000);
})

$('.close').click(function(){
$('.paragraph').animate({'height':'0px'},1000);
})
</script>

</body>
</html>

2 个答案:

答案 0 :(得分:0)

将您的代码更改为:

<script>
    $('h1.heading').click(function(){
    $(this).next().animate({'height':'50px'},1000);
    })

    $('.close').click(function(){
    $('.paragraph').animate({'height':'0px'},1000);
    })
    </script>

答案 1 :(得分:0)

{em} {/ 1}}

之后需要 <body>代码

另外,你可能应该这样做:

</head>

否则这些元素将在某些浏览器中保持可见和重叠。