如何将jquery效果应用于嵌套元素?

时间:2010-09-15 20:56:17

标签: jquery

我正在制作一个简单的常见问题解答页面,该页面将显示/隐藏点击问题的答案。它在使用p元素时工作正常,除了任何嵌套的ul元素都没有被隐藏之外没有别的。嵌套元素是否必须单独调用?为什么效果不作为p标签的一部分应用于它?谢谢你的帮助。

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js" type="text/javascript"></script> 

 <script language="javascript" type="text/javascript">

$(document).ready(function () {
    $(".answer").hide();
    $("a.question").click(function () {
      $(this).next(".answer").slideToggle(300);
      return false;
    });
 });
</script> 
<div id="body"> 
<ul style="list-style: none;"> 
<li><a class="question" href="#">How do I log in to email?</a> 
<p class="answer">
    <ul>
        <li>Open your favorite internet browser to <a href="https://email.school.edu">email.school.edu</a>.</li>
        <li>Use your school username and the password given to you by ITS.</li>
        <li>You will be required to change your password immediately.</li>
    </ul>
</p> 
</li> 
<li><a class="question" href="#">Is my email password the same as my school password?</a> 
<p class="answer">No. After logging in to email for the first time, you will be required to change your password. It is your option to use the same password or create another password; however, ITS strongly encourages you to create a <strong>Strong</strong> password as indicated on the status bar in the email password site. Keep in mind that if you change your school password, your email password will not change and vice versa.</p> 
</li> 
</ul>
</div>

截图 alt text

2 个答案:

答案 0 :(得分:5)

它与浏览器处理段落标记的方式有关。如果您在Firebug中检查当前设置,您会看到Firefox不会将ul解释为孩子。但是,如果您切换到div,它将正常工作。显示在:http://jsfiddle.net/4q9Dp/

答案 1 :(得分:2)

为了扩展BBonfield的观点,问题在于&lt; ul&gt;是一个块级元素。 &lt; p&gt; element不能包含块级元素(有关此W3C​​定义,请参阅http://www.w3.org/TR/html401/struct/text.html#h-9.3.1)。因此,浏览器自动关闭&lt; p&gt; &lt; ul&gt;之前的标记开始。解决方案是使用&lt; div&gt;标记,用于文档中的逻辑分区。

关于内联和块级元素之间差异的有用教程:http://webdesign.about.com/od/htmltags/qt/block_vs_inline_elements.htm