简体   繁体   English

jQuery .slideToggle - 以某种方式被触发多次

[英]jQuery .slideToggle – Somehow being triggered multiple times

Here's my code, I've tried to cut anything unnecessary from the JS: http://codepen.io/Zacaree/pen/EmZJXy 这是我的代码,我试图从JS中删除任何不必要的东西: http//codepen.io/Zacaree/pen/EmZJXy

When I click one of the dropdown buttons (right side of page) triggering jQuery's .slideToggle, it opens a drawer but instead of remaining open, the drawer will trigger multiple times. 当我单击其中一个下拉按钮(页面右侧)触发jQuery的.slideToggle时,它会打开一个抽屉但不会保持打开状态,抽屉会多次触发。 The number of times triggered increases with each successive panel down the page. 触发的次数随着每个连续面板向下移动而增加。

The uppermost panel always works correctly. 最上面的面板始终正常工作。

function foo() {    
    $('.dashboard-right').children('h1').after(functionContainer).siblings('.function-container').removeClass('isPaused');

    $('.dropdown-button').click(function(){
        $(this).parents('.function-footer').siblings('.log-container').slideToggle('fast');
        $(this).children('.arrow').toggleClass('active');
    });
};

foo();
foo();
foo();
foo();
foo();

I'm a designer not a developer so please forgive me for posting what's probably a simple error on my part. 我是设计师而不是开发人员,所以请原谅我发布可能是一个简单的错误。 I've fought and fought with this and can't seem to figure it out. 我已经与此作斗争并且无法解决这个问题。 Thank you so much to anyone who can explain to me what I'm doing wrong! 非常感谢能够向我解释我做错了什么的人!

Thank you! 谢谢!

You are binding a click event every single time foo is called (Since the method is called 5 times, 5 click events are being bound to that element ) 每次调用foo都绑定一个click事件(因为该方法被调用了5次,所以5个click事件被绑定到该元素)

You need to just bind the click event only once. 您只需要将click事件绑定一次。

Move the click binding event to outside of the foo method. 将单击绑定事件移动到foo方法之外。

http://codepen.io/anon/pen/QvpLeg http://codepen.io/anon/pen/QvpLeg

function foo() {    
    $('.dashboard-right').children('h1')
                        .after(functionContainer)
                        .siblings('.function-container')
                        .removeClass('isPaused');
  };

$('body').on('click', '.dropdown-button' ,function() {
      $(this).parents('.function-footer')
             .siblings('.log-container')
             .slideToggle('fast');

      $(this).children('.arrow').toggleClass('active');
});

  foo();
  foo();
  foo();
  foo();
  foo();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM