简体   繁体   English

事件侦听器内的函数仅在其初始化时触发

[英]Function inside event listener triggers only on it's initialization

 var init = true; $('#btn').on('click', delay(function() { $('#text').append('click'); init = false; }, 100)); function delay(fn, ms, enabled = true) { $('#text').append(init); // if(init) disable delay let timer = 0; return function(...args) { clearTimeout(timer); timer = setTimeout(fn.bind(this, ...args), ms || 0); } }
 <script src="https://code.jquery.com/jquery-3.1.0.js"></script> <button id='btn'> TRIGGER </button> <div id="text"></div>

Init is a global variable which is meant to be used inside delay function to disable delay (init true/false) only on event listener initialisation. Init 是一个全局变量,用于内部延迟函数以仅在事件侦听器初始化时禁用延迟(init true/false)。

The problem is that the delay function is triggered only once and ignores the change (to false) of the init variable.问题是延迟函数只被触发一次,并忽略了 init 变量的变化(为 false)。

For example, try clicking the trigger button.例如,尝试单击触发按钮。 The init variable value is printed only for the first time. init 变量值仅在第一次打印。

You are calling the delay function in a wrong way in the click handler.您在单击处理程序中以错误的方式调用延迟函数。 You have to call it like so:你必须这样称呼它:

$('#btn').on('click', function () {

    delay(function() {

        $('#text').append('click');
        init = false;

    }, 100);
});

You will have to check for the value of init inside the function, like this:您必须检查函数内init的值,如下所示:

$('#btn').on('click', delay(function() {

if(init) {
  $('#text').append('click');
  init = false;
  }

}, 100));

At the moment I don't know why append is not working but with a little workaround you can obtain what you want.目前我不知道为什么 append 不起作用,但通过一些解决方法,您可以获得所需的内容。 Concatenate the original text and the actual one and use text() to set it again:连接original文本和actual text()并使用text()再次设置它:

 var init = true; $('#btn').on('click', function() { $('#text').text(init); setTimeout(myDelay, 5000); }); function myDelay() { let originalText = $('#text').text(); init = false; console.log("init is false"); console.log("original text displayed: " + originalText); $('#text').text(originalText + " " + init); }
 <script src="https://code.jquery.com/jquery-3.1.0.js"></script> <button id='btn'> TRIGGER </button> <div id="text"></div>

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

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