我需要帮助试图弄清楚为什么这只会隐藏和显示我的隐藏类的所有元素。我尝试过这样做:
$("h2 > p").removeClass("hidden");
当我使用它时,它根本不起作用。我也尝试过:
$(this).find('p').removeClass("hidden");
这也根本行不通。由于这是作业,我无法直接编辑 CSS 或 HTML,而且这是对 JQuery 的介绍,因此实际的 JavaScript 和 JQuery 根本不应该高级。我只是不明白为什么它不适用于我上面展示的两个示例。我所需要的只是要显示的答案之一,而不是每一个。
$(document).ready(function() {
$("h2").on('mouseover', function() {
$("p").removeClass("hidden");
});
$("h2").on('mouseout', function() {
$("p").addClass("hidden");
});
}); // end ready
这是 HTML 部分,包括我尝试添加和删除的类。
<body>
<section>
<h1>jQuery FAQs</h1>
<ul id="faq_rollovers">
<li><h2>What is jQuery?</h2>
<p class="hidden">jQuery is a library of the JavaScript functions
that you're most likely to need as you develop web sites.</p>
</li>
<li><h2>Why is jQuery becoming so popular?</h2>
<p class="hidden">Three reasons: It's free; It lets you get more done
in less time; All of its functions are cross-browser compatible.</p>
</li>
<li><h2>Which is harder to learn: jQuery or JavaScript?</h2>
<p class="hidden">For most functions, jQuery is significantly easier to learn
and use than JavaScript. But remember that jQuery is JavaScript.</p>
</li>
</ul>
</section>
注意:由于 p 元素是隐藏的,并且您实际上无法将鼠标悬停在其上,因此我选择使用 h2 元素作为鼠标悬停选择器。
最佳答案
您的问题是 p 标签不在 h2 标签内。您可以执行以下任一操作:
$(this).siblings("p").removeClass("hidden");
或者:
$(this).parent().find("p").removeClass("hidden");
关于javascript - JQuery 隐藏/显示一个,而不是全部,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33879620/