【问题标题】:Expand <p> when <h1> is clicked单击 <h1> 时展开 <p>
【发布时间】:2011-07-16 05:13:43
【问题描述】:

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

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

我以前从未使用过 jQuery 或 JavaScript,所以如果您能稍微解释一下此切换代码的​​工作原理,那就太好了。谢谢。

【问题讨论】:

  • 谢谢大家的回答。非常感谢您的帮助。

标签: javascript jquery html css


【解决方案1】:

嗯,应该这样做:

$(function() {

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

});

现在让我解释一下代码。

第一行接受一个函数,该函数将在文档完成加载后运行。相当于:

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

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

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

干杯!

【讨论】:

  • +1 与其他答案不同,这只会在单击&lt;h1&gt; 后切换&lt;p&gt;,而不是文档中的所有&lt;p&gt;s。
  • $(this).find("p").toggle() 会找到h1下的所有P标签
  • $(this).find("p").eq(1).toggle() 我认为是另一种选择
  • $(this).find("p:first").toggle() 另一种选择
  • @kasdega:你可以把它浓缩成$(this).find("p:eq(1)").toggle();
【解决方案2】:

使用toggle

$('h1').bind('click', function(){
    $('p').toggle();
});

【讨论】:

  • 这将找到并切换页面上的所有

    标签

  • 当然。并将绑定到每个&lt;h1&gt;
【解决方案3】:

DEMO

<head>
  <!-- other content, including jQuery script tag -->
  <script type="text/javascript">
    $(function(){ // trigger when document's ready

      // hide the pragraph initially
      $('p').hide();

      // add a click event to the header so we can hide/show the paragraph
      $('h1').click(function(e){
        // $(this) is the header, next finds the next paragraph sibling (they're both
        // withint he div, so the header and div are known as siblings) then toggle
        // toggles if this found paragraph should be shown or hidden
        $(this).next('p').toggle();
      });
    });
  </script>
</head>

单击 DIV 会指示 jQuery 查找作为段落的“下一个”元素(因为标题和段落是同一节点的兄弟姐妹)然后 toggles 它。

我还在代码中添加了隐藏,因为在我看来,最好从 javascript 中隐藏内容,这样即使它们不支持 javascript,也不会丢失任何内容。其他人使用 CSS 样式,只使用 javascript 显示,这很好,但如果他们在页面上没有或禁用 JS,则无法再次查看该内容。

【讨论】:

【解决方案4】:

试试这个

$("h1").click(function(){
    $("p").slideToggle(500);
});

【讨论】:

  • 这将找到并切换页面上的所有

    标签

  • 根据他的标记,这只是一个指针。他必须相应地对其进行编码。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-07-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多