我需要一个可以重新使用的单个jQuery函数来单独切换多个元素。jQuery页面上的http://api.jquery.com/slidetoggle/代码示例对于使用按钮的单个元素很好,但对于使用非按钮元素的多个元素则不起作用。
我的代码(改编自jQuery幻灯片切换示例):
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>slideToggle demo</title>
<script src="http://code.jquery.com/jquery-2.1.1.min.js"></script>
</head>
<body>
<div class="first">Toggle first</div>
<p class="first">First hidden paragraph.</p>
<div class="second">Toggle second</div>
<p class="second">Second hidden paragraph.</p>
<script>
$( "div.first" ).click(function() {
$( "p.first" ).slideToggle(0);
});
</script>
<script>
$( "div.second" ).click(function() {
$( "p.second" ).slideToggle(0);
});
</script>
</body>
</html>代码允许每个元素单独切换,这正是我想要的。但是,我的代码有两个问题:
我一直未能找到解决这两个问题的直截了当的办法。任何帮助都将不胜感激。
发布于 2014-07-04 05:55:09
对事件源的所有集合使用相同的类。对于n个html集,您只能有效地使用两个类。
<div class="first">Toggle first</div>
<p class="first-p">First hidden paragraph.</p>
<div class="first">Toggle second</div>
<p class="first-p">Second hidden paragraph.</p>将当前对象与next()一起使用
$('.first-p').hide();
$( "div.first" ).click(function() {
$(this).next().slideToggle(1000);
});发布于 2014-07-04 06:51:08
$(function () {
$(".first, .second")
.filter("p")
.toggle()
.addBack()
.not("p")
.click(function (e) {
return $("." + e.target.className).not("div").slideToggle(0)
});
});https://stackoverflow.com/questions/24567542
复制相似问题