展开< p>当< h1>被点击 [英] Expand <p> when <h1> is clicked

查看:88
本文介绍了展开< p>当< h1>被点击的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用JavaScript进行非常简单的展开/折叠,当我点击标题时,它会显示文本(当页面首次加载时被隐藏)。此外,当我再次点击标题时,我想要文本再次隐藏。

I want to do a very simple expand/collapse using JavaScript where when I click "Title", it shows "Text" (which is hidden when the page first loads). Furthermore, when I click on the "Title" again, I want "Text" to get hidden again.

<div>
    <h1>Title</h1>
        <p>Text</p>
</div>

我从来没有使用jQuery或JavaScript,所以如果你能解释一下关于这个切换代码的​​工作原理。感谢。

I've never used jQuery or JavaScript before so it would be great if you can explain just a little bit about how this toggle code works. Thanks.

推荐答案

这应该可以:

$(function() {

    $('h1').click(function() {
        $(this).next('p').toggle();
    });

});

现在让我解释一下代码。

So now let me explain the code.

第一行接受一个函数,当文档加载完成后运行。它等价于:

The first line is accepting a function that will run when the document has finished loading. It is equivalent to:

$(document).ready(function() {
    // Stuff to do when the document is ready.
});

中间的代码表示, h1 元素,当它被点击时,执行一个函数,找到它旁边的 p 元素,并切换其可见性。第一个选择器中的 this 指的是实际的< h1> DOM元素。我这样做,所以如果你有一个结构,如下所示,切换只会影响段落旁边的内容。

The code in the middle says, for every h1 element, when it gets clicked, execute a function that finds the p element next to it and toggle its visibility. The this in the first selector refers to the actual <h1> DOM element. I did it this way so if you had a structure like the following, the toggling would only affect the content next to the paragraphs.

<div>
    <h1>Section 1</h1>
    <p>Section 1 Content</p>
</div>
<div>
    <h1>Section 2</h1>
    <p>Section 2 Content</p>
</div>

干杯!

这篇关于展开&lt; p&gt;当&lt; h1&gt;被点击的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆