【问题标题】:JQuery Hide/Show one, not allJQuery 隐藏/显示一个,而不是全部
【发布时间】:2015-11-23 20:01:00
【问题描述】:

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

$("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 元素作为鼠标悬停选择器。

【问题讨论】:

  • hidden 类添加了哪些样式?你试过$("li p.hidden").show()吗?
  • 您可以在 jQuery 中仅使用一个处理程序而不是两个处理程序来执行此操作,或者甚至根本不需要任何 JavaScript,只需使用 CSS。如果你想知道怎么做,请告诉我。

标签: javascript jquery html show-hide mouseleave


【解决方案1】:

您的问题是 p 标签不在 h2 标签内。你可以这样做:

$(this).siblings("p").removeClass("hidden");

或者:

$(this).parent().find("p").removeClass("hidden");

【讨论】:

  • 非常感谢!我总是忘记兄弟姐妹和父母(即使在 CSS 中)。
【解决方案2】:

尝试在其他 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

【讨论】:

  • 谢谢!这帮了我很多忙!我总是忘记父母、兄弟姐妹和孩子!
【解决方案3】:

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

【讨论】:

  • 你可以使用 .hover() 函数。
猜你喜欢
  • 2019-08-22
  • 2017-05-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-04-30
  • 2020-05-20
  • 2015-03-03
  • 1970-01-01
相关资源
最近更新 更多