防止在元素上触发新事件,直到当前事件函数在jQuery中完成

Prevent new events be triggered on an element until currently event function finishes in jQuery

本文关键字:事件 函数 jQuery 元素 新事件      更新时间:2023-09-26

考虑以下内容:

$('#theElement').on('click',function(){
  $(this).animate(...);
  $(this).doThis(...);
  $(this).doThat(...);
  $('anotherElement').animate(...);
  $('anotherElement').doThis(...);
  $('anotherElement').doThat(...);
});

正如您所看到的,这里是onClick事件的一个简单委托函数。现在,如何在执行该函数的过程中,在"#theElement"上不触发其他事件?

我尝试使用preventDefualt(),但它停止了整个执行,这意味着animate()、doThis()等也不会运行。

在函数启动时在元素上设置布尔标志。

$('#theElement').on('click',function(){
    $(this).data('flagname',true);
    // ...

在其他事件中测试标志。

if (!$(this).data('flagname')) {  // !(undefined) is true
   // run code
}

动画完成后清除标志。

var $this = $(this); // 'this' is locally scoped
$this.animate(/* ... */, function() { 
    $this.data('flagname',false);
});

你必须像这样嵌套它们:

$(".yourclass").animate({}, time, function(){
   $(".yoursecondclass").animate({}, time, function(){
   });
});