简体   繁体   English

如何防止JS中多次调用function

[英]How to prevent multiple function call in JS

I am new to JS and I need to execute my function in 1 click and all other clicks after the first are ignored.我是 JS 新手,我需要单击一次执行我的 function,第一次单击之后的所有其他单击都将被忽略。

 let count = 0; function func() { if (count == 0) { console.log("First Click"); let count = 1; } else { console.log("No first Click"); } }
 <button onclick="func()">Func</button>

(not working) (不工作)

Remove let keyword删除 let 关键字

Try this:尝试这个:

<script>
  count = 0;

function func() {
  if (count == 0) {
    alert("first");
    console.log("First Click");
     count = 1;
  } else {
    alert("no first");
    console.log("No first Click");
  }
}
</script>

https://jsbin.com/toroyiropa/edit?html,output https://jsbin.com/toroyiropa/edit?html,output

Something like this should work:像这样的东西应该工作:

<button onclick="func()">Func</button>
<script>
  let count = 0;

  function func() {
    if (count == 0) {
      console.log("First Click");
      count = 1;
    } else {
      console.log("No first Click");
    }
  }
</script>

Explanation: Here count is a global variable you need to change its value once to something different than your comparator ie (count == 0).说明:这里的 count 是一个全局变量,您需要将其值更改为与比较器不同的值,即(count == 0)。

I'll suggest you to do something like this:我会建议你做这样的事情:

<button onclick="func()">Func</button>
<script>
   var enabled = true;

   function func() {
      if (enabled) {
         console.log("Do something");
         enabled = false;
      }
   }
</script>

To work with a persistent variable in the context you just need to change the variable from let to var.要在上下文中使用持久变量,您只需将变量从 let 更改为 var。 This solution should work and also might be a little bit cleaner because I think that you probably don't need to use a counter to check if you already perform the function, it's an extra effort.这个解决方案应该可以工作,而且可能更干净一些,因为我认为您可能不需要使用计数器来检查您是否已经执行了 function,这是一项额外的工作。

To have the count variable persist across every function call, the best way is to use closures.要让计数变量在每个 function 调用中保持不变,最好的方法是使用闭包。

<button onclick="func()">Func</button>

<script>

  var clickTrack = (function() {
    var count = 0;
    return function() {
        if (count == 0) 
            console.log("First Click");
      else
            console.log("No first click");
      count++;
        return;
     }
   })();

  function func() {
        clickTrack();

  }

 </script>

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

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