javascript - 切换单击的任意元素

标签 javascript jquery toggle

我将toggle()与jQuery一起使用,我的页面上有一个侧边栏,每个标题是

<h2 class="sidebar-header">

我的代码的一部分如下所示:

    <div class="sidebar-section">   
        <h2 class="sidebar-header">SUBSCRIBE</h2>
        <p class="sidebar">Make sure you subscribe to stay in touch with the latest articles and tutorials. Click on one of the images below:</p>
        <div class="rss-icons">
            <a href="http://fusion.google.com/add?feedurl=http://feeds.feedburner.com/ryancoughlin"><img src="http://gmodules.com/ig/images/plus_google.gif" width="62" height="17" alt="Add to Google Reader or Homepage" class="feed-image"/></a> 
            <a href="http://add.my.yahoo.com/rss?url=http://feeds.feedburner.com/ryancoughlin" title="Web/Graphic Design/Development by Ryan Coughlin"><img src="http://us.i1.yimg.com/us.yimg.com/i/us/my/addtomyyahoo3.gif" alt="Add feed to My Yahoo" width="62" height="17" class="feed-image" /></a>
            <a href="http://www.newsgator.com/ngs/subscriber/subext.aspx?url=http://feeds.feedburner.com/ryancoughlin" title="Web/Graphic Design/Development by Ryan Coughlin"><img src="http://www.newsgator.com/images/ngsub1.gif" alt="Subscribe in NewsGator Online" class="feed-image" height="17" /></a>
        </div>
        <hr />
        <p class="sidebar feed">Don't have those? Grab the <a href="http://feeds.feedburner.com/ryancoughlin" target="_blank" title="Subscribe to this feed">RSS</a> url.</p>
        <p class="sidebar delicious">Make sure you add me to <a href="http://del.icio.us/post?url=http://www.ryancoughlin.com&amp;title=Ryan Coughlin - Web/Graphic Design and Development" target="_blank" title="Add to delicious!">delicious!</a> </p>
    </div>

它们都包含在那些 DIV 元素中。我试图做到这一点,因为如果您单击标题,它会缩小内容。我知道切换可以做到这一点,但如果我为每个“侧边栏标题”制作它,您将单击页面上的任何一个元素,它将隐藏所有元素,我该怎么做?

最佳答案

尝试这样的事情:

假设您有以下代码:

<div class="topdiv">
    <h2 class="header">Header 1</h2>
    <div class="somecontent">
        This is the content
    </div>
</div>

<div class="topdiv">
    <h2 class="header">Header 2</h2>
    <div class="somecontent">
        This is the content
    </div>
</div>

现在,假设当您要单击标题时,该标题的内容将显示/隐藏:

$(".header").click(function () {
    $(this).parent(".topdiv:first").find(".somecontent").toggle();
});

这样,只有特定 header 的内容会被切换,而不是其余的。

现在您可以分析我为您编写的代码,并将其应用到您自己的上下文中。

关于javascript - 切换单击的任意元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/383739/

相关文章:

javascript - 记住切换状态 JavaScript 冲突

javascript - 发送前在DataTable上添加ajax数据

javascript - 加载远程 HTML 时如何正确延迟 jQuery 动画?

javascript - HighCharts Semi-Circle-Donut,去除边距和填充

jquery - 一个元素的CSS过渡左右位置

javascript - 如何从 javascript 函数返回 true 和值?

css - 在纯 CSS 中切换,带有一个子元素

javascript - 如何将隐藏的<dl>元素一个一个显示或者同时全部显示?

javascript - ionic 2 本地存储无法将检索到的值设置为变量

javascript - 水平滚动不适用于 iPhone