简体   繁体   English

使用 javascript 处理一系列点击

[英]Handling a sequence of clicks with javascript

When using plain javascript to handle the clicking of a button, I have the following problem.当使用普通 javascript 处理按钮的点击时,我遇到以下问题。

I have generic code like this:我有这样的通用代码:

let count = 0
myButton.onclick = function() {
    if (count > 2 {
        ... do something special ...
        // This does not work!!
    }
    ...
    count++
}

It is basically working, but I want to be able to make the difference between the first click and the second, third..etc..它基本上可以正常工作,但我希望能够区分第一次点击和第二次点击、第三次点击等等。

I would only need to have some kind of variable starting with the value 0 (for instance) and getting incremented on each click.我只需要有某种以值 0 开头(例如)并在每次点击时递增的变量。

What is the correct way to implement such a variable?实现这种变量的正确方法是什么?

What instinctively came to mind at this point (roughly 2 solutions) has failed.此时本能想到的(大约 2 个解决方案)都失败了。

You should increment the count before if condition then it will give you your desired result.你应该在if条件之前增加计数,然后它会给你你想要的结果。 Your code will also work but on 4th click, this will give you a better idea of how it is working:您的代码也可以工作,但在第 4 次点击时,这会让您更好地了解它是如何工作的:

 var count = 0 myButton = document.getElementById("mybutton"); myButton.onclick = function() { console.log('Initial Count is', count); if (count > 2) { //This is checking if initial count is > 2 console.log("Executed"); } count++; console.log('Incremented Count is', count); }
 <,DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width. initial-scale=1.0"> <link rel="stylesheet" href="src/style.css"> </head> <body> <h1 id="header"></h1> <button id="mybutton">Click</button> </body> </html>

<input type="button" id="myButton" value="Add" />
<script>
var x = 0;
let btn_element = document.getElementById("myButton");

btn_element.onclick = () => {
     if(x>2)    
    {
      console.log("Task is performed", x);   
    }           
     x++;
    
};
</script>

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

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