【发布时间】:2010-05-12 05:36:04
【问题描述】:
我正在使用一些 jQuery 来展开/隐藏一些 div。我需要添加一个事件处理程序,以便在单击链接时打开一个对应的 div。每个切换的 div 都将分配一个唯一的类。我正在寻找有关如何构建事件处理程序的一些建议。
jQuery
$(document).ready(function(){
$(".toggle_container:not(:first)").hide();
$(".toggle_container:first").show();
$("h6.trigger:first").addClass("active");
$("h6.trigger").click(function(){
$(this).toggleClass("active");
$(this).next(".toggle_container").slideToggle(300);
});
CSS:
// uses a background image with an on (+) and off (-) state stacked on top of each other
h6.trigger { background: url(buttonBG.gif) no-repeat;height: 46px;line-height: 46px;width: 300px;font-size: 2em;font-weight: normal;}
h6.trigger a {color: #fff;text-decoration: none; display: block;}
h6.active {background-position: left bottom;}
.toggle_container { overflow: hidden; }
.toggle_container .block {padding: 20px;}
html中有一个链接列表,如:
<a href="#">One</a>
<a href="#">Two</a>
以及要打开的相应 div:
<h6 class="trigger">Container one</h6>
<div class="toggle_container">
div one
</div>
<h6 class="trigger">Container two</h6>
<div class="toggle_container Open">
div one
</div>
正如我所提到的,我将分配一个独特的类来促进这一点。
有什么建议吗?谢谢!
- 为了澄清,我正在寻找一些建议来构建一个事件处理程序,以在从页面的不同部分(例如从导航)单击链接时切换打开特定 div。
【问题讨论】:
-
您的代码看起来不错。你在问问题吗?
-
使用
$("div.toggle_container").hide().first().show()而不是$(".toggle_container:not(:first)").hide(); $(".toggle_container:first").show();将减少大约 0.00001 毫秒的执行时间......如果我非常挑剔:) -
是的,抱歉,可能不清楚(脑筋急转弯)。我已经更新了我的问题以更清楚。单击
时,上面的代码效果很好。我想弄清楚如何为这个 div 切换器分配另一个类并触发它从页面上其他位置的链接打开。
标签: jquery html event-handling toggle