jQuery click会记住我多次点击和触发多次

时间:2018-02-05 22:27:21

标签: javascript jquery onclick fadein fadeout

我有一个按钮,用输入文本切换可见链接或表单。当我多次快速点击它时出现问题,搜索的输入只是像疯了一样闪烁,每次点击按钮都会淡入淡出,我想阻止它多次点击。

我该怎么做?

   $("#search-button").on("click", function (e) {
       e.stopPropagation();
       e.stopImmediatePropagation();
       e.preventDefault();

       $("#search-form").fadeToggle(800);

       if (links.css('visibility') === 'hidden')
           links.css('visibility', 'visible');
       else
           links.css('visibility', 'hidden');

   });

2 个答案:

答案 0 :(得分:0)

您可以停用点击处理程序,直到动画结束,然后重新激活它。



var toggleSearch = function(e) {
  $("#search-button").off("click"); // When the click is received, turn off the click handler

  e.stopPropagation();
  e.stopImmediatePropagation();
  e.preventDefault();
  $("#search-form").fadeToggle(800, function() {
    $("#search-button").on("click", toggleSearch); // When the animation is finished, turn the click handler on again
  });
/*
  if (links.css('visibility') === 'hidden')
    links.css('visibility', 'visible');
  else
    links.css('visibility', 'hidden');
*/
}

$("#search-button").on("click", toggleSearch);

#search-form {
  width: 200px;
  height: 100px;
  background-color: #f90;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button type="button" id="search-button">search-button</button>
<form id="search-form">

</form>
&#13;
&#13;
&#13;

答案 1 :(得分:-1)

除了了解可观察或贬低的兔子洞之外,you can probably steal David Walsh's debounce function

辩护人

// Returns a function, that, as long as it continues to be invoked, will not
// be triggered. The function will be called after it stops being called for
// N milliseconds. If `immediate` is passed, trigger the function on the
// leading edge, instead of the trailing.
function debounce(func, wait, immediate) {
    var timeout;
    return function() {
        var context = this, args = arguments;
        var later = function() {
            timeout = null;
            if (!immediate) func.apply(context, args);
        };
        var callNow = immediate && !timeout;
        clearTimeout(timeout);
        timeout = setTimeout(later, wait);
        if (callNow) func.apply(context, args);
    };
};

实现:

var myDebouncer = debounce(function() {

    // Put your original code here

}, 250);

window.addEventListener('resize', myDebouncer);

您现在可以通过传递此操作来解除应用中的任何其他操作。