JQuery隐藏/显示一个,而不是全部

JQuery Hide/Show one, not all

本文关键字:一个 全部 隐藏 显示 JQuery      更新时间:2023-09-26

我需要帮助来弄清楚为什么这只会隐藏和显示我隐藏类的所有元素。我试过做:

$("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");

尝试在另一个h2中搜索p标签:

$(document).ready(function() {
    $("h2").on('mouseover', function() {
        $(this).siblings("p").removeClass("hidden");
    });
    $("h2").on('mouseout', function() {
        $(this).siblings("p").addClass("hidden");
    });
}); // end ready

$( "h2" ).hover( function() {
  $(this).next().removeClass("hidden");
}, function() {
  $(this).next().addClass("hidden");
});

相关文章: