javascript - 如何在javascript中延迟先前绑定(bind)的事件?

标签 javascript

我有一个按钮,单击时执行特定操作,该操作来自框架默认操作。我想延迟该功能(我不知道该按钮绑定(bind)在哪里,我无法修改它)

为了简单起见,我将在这里提供具有两种不同功能的示例:

// lets say, this is the function which is bound from the framework, and I can't change:
$('button').on('click', function() {
  console.log('default click action');
});


// and I want to delay the action of the previous bound function from a new function without modifying the previous one, something like this:

$('button').on('click', function() {
  console.log('delayed both events for 1s'); // delay both of them for 1s.
});
button {
  border: 1px solid #cecece;
  padding: 5px 15px;
  font-size: 14px;
  border-radius: 4px;
  font-weight: bold;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button type='button'> Try </button>

注意:函数执行的顺序不必改变,第一个函数可以先执行,没问题。但我需要能够延迟第二个函数的第一个函数的执行。

最佳答案

我的想法是下一个:

如果您有这样的选项来修改元素结构 - 您可以尝试用某些元素(例如 span)包装您的 button 并为 注册一个监听器在捕获阶段对其进行 code>click 事件(请阅读有关 addEventListeneruseCapture 参数的更多信息。

当您在此类包装器上捕获 click 事件时(这将在您的框架处理程序处理之前) - 您可以停止此事件传播并触发新的自定义 click 事件使用 setTimeout 1 秒后。

// lets say, this is the function which is bound from the framework, and I can't change:
$('button').on('click', function() {
  console.log('default click action');
});

// and I want to delay the action of the previous bound function from a new function without modifying the previous one, something like this:


document.querySelector('.button-wrapper').addEventListener('click', function(event) {
  if (!event.detail || !event.detail.delayed) {
    event.stopPropagation();
    setTimeout(function(button) {
      button.dispatchEvent(new CustomEvent('click', {detail: {delayed: true}}));
      console.log('delayed both events for 1s');
    }, 1000, this.children[0]);
  }
}, true);
button {
  border: 1px solid #cecece;
  padding: 5px 15px;
  font-size: 14px;
  border-radius: 4px;
  font-weight: bold;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<span class="button-wrapper"><button type='button'> Try </button></span>

关于javascript - 如何在javascript中延迟先前绑定(bind)的事件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53129245/

相关文章:

javascript - 如何动态使用ng-for获取输入框和复选框

javascript - @grid MVC 将日期转换为本地时区

javascript - 当我在函数参数 : Why is that? 中声明新变量时出现错误

javascript - JQuery 应用绑定(bind)到所有 child

javascript - javascript中的小数减法问题

javascript - 在Javascript中,为什么要定义一个带有split的数组?

javascript - 使用 chrome 扩展修改加载页面的 HTML

javascript - 使用按钮 onclick 时不显示警报

javascript - Jquery,防止重定向,验证然后提交表单

javascript - MathJax 不呈现 "less-than sign"