Javascript 切换单击的元素
我在jQuery中使用toggle(),我的页面上有一个侧栏,每个标题都是Javascript 切换单击的元素,javascript,jquery,toggle,Javascript,Jquery,Toggle,我在jQuery中使用toggle(),我的页面上有一个侧栏,每个标题都是 <h2 class="sidebar-header"> 我的代码的一部分如下所示: <div class="sidebar-section"> <h2 class="sidebar-header">SUBSCRIBE</h2> <p class="sidebar">Make sure you subscribe
<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&title=Ryan Coughlin - Web/Graphic Design and Development" target="_blank" title="Add to delicious!">delicious!</a> </p>
</div>
订阅
没有吗?抓取url
它们都被包装在那些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>
这样,只切换特定标题的内容,而不切换其余内容
现在,您可以分析我为您编写的代码,并将其应用到您自己的上下文中。尝试以下方法:
这似乎奏效了!nextAll()的工作原理很有趣,我仍然对它的工作原理感到困惑,兄弟姐妹们?我知道这有点“宽泛”,但是,这到底是什么意思呢?谢谢,当您调用“nextstall”时,maxjQuery使用“nextSibling”DOM元素属性。还有一个简单的“while”循环来扫描当前元素之后的所有同级元素。您甚至可以在jQuery sources中自己探索它:找到“nextAll”,然后查看相应的“dir”调用:),因此这将在您单击.header时起作用,它将获取该元素和div.topdiv的父元素并查找.somecontent,然后应用切换?对的谢谢你的帮助!RyanYes,它将找到单击的标题,遍历到具有“topdiv”类的父div,然后遍历到具有“somecontent”类的“topdiv”的子元素,并切换它。
$(".header").click(function () {
$(this).parent(".topdiv:first").find(".somecontent").toggle();
});
$(".sidebar-header").click(function() {
$(this).nextAll().toggle();
});