使用 jquery 制作我自己的手风琴风格切换
我在 js 中有一个 var 保存点击操作。这个动作绑定到几个不同的 div:
<div class="clickable"><div class="hidden">inner content 1</div></div>
<div class="clickable"><div class="hidden">inner content 2</div></div>
<div class="clickable"><div class="hidden">inner content 3</div></div>
js 看起来像这样:
$(document).ready(function(){
var clicker = function(){
$('.hidden').slideUp();
$(this).children('.hidden').slideDown();
$(this).unbind('click',clicker);
}
$('.clickable').bind('click',clicker);
});
上面的代码基本上可以工作。如果我单击 div.clickable 它会显示隐藏内容。如果我单击另一个 div.clickable,它会隐藏我刚刚查看的内容并显示另一个内容。然而问题是,由于“点击器”内的取消绑定功能,我单击的任何内容都会失去其点击器功能。我这样做是因为隐藏内容具有可点击的内容,并且我现在在隐藏内容中点击的任何内容都会再次触发“点击器”。
不使用手风琴插件的更智能方法是什么?
如何检查 div 是否已绑定到函数,如果没有,则重新绑定它或类似的操作?我所寻找的只是在 div.clickable 关闭后将其重新绑定到“clicker”,即正在查看另一个 div.clickable .hidden 。
I have a var in js which holds a click action. This action is bound to a few different divs:
<div class="clickable"><div class="hidden">inner content 1</div></div>
<div class="clickable"><div class="hidden">inner content 2</div></div>
<div class="clickable"><div class="hidden">inner content 3</div></div>
The js looks like so:
$(document).ready(function(){
var clicker = function(){
$('.hidden').slideUp();
$(this).children('.hidden').slideDown();
$(this).unbind('click',clicker);
}
$('.clickable').bind('click',clicker);
});
The above code basically works. If i click a div.clickable it shows the hidden content. If I click another div.clickable, it hides the content I was just looking at and reveals another one. The problem however is that because of that unbind function inside 'clicker' anything I click loses its clicker functionality. I did this because the hidden content has clickable stuff, and anything I now click inside the hidden content triggers off 'clicker' again.
Whats the more intelligent approach to this without using the accordion plugins?
How can I check to see if a div has been bound to a function, and if not, rebind it or something of the sort? All I am looking for is to rebind the div.clickable to 'clicker' once its been closed ie another div.clickable .hidden is being looked at.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以只排除您在
.slideUp()
,像这样:通过使用
.not()
我们排除.hidden
中要隐藏的当前元素,并在显示子元素时将其限制为仅:hidden
元素意味着我们不会重新滑动任何已经可见的元素。另一种更简单地重写它的方法是:
或者,如果它们所有
.clickable
元素都是兄弟元素:You can just exclude the one you're clicking on in the
.slideUp()
, like this:By using
.not()
we're excluding the current element in the.hidden
ones to hide, and when showing children restricting it to only:hidden
elements means we won't re-slide any that are already visible.Another way to re-write it a bit more plainly is:
Or, if they all
.clickable
elements are siblings: