最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to get alert message on second click of a button - Stack Overflow

programmeradmin3浏览0评论

I would like to know that how can I get an alert message on second click of a button, not on a first click.

ex: <input type="button" value="Message" onclick="showMessage()">

function showMessage(){
    alert("It's a second click message"); // this alert message should be shown on second click of a button
}

I would like to know that how can I get an alert message on second click of a button, not on a first click.

ex: <input type="button" value="Message" onclick="showMessage()">

function showMessage(){
    alert("It's a second click message"); // this alert message should be shown on second click of a button
}
Share Improve this question edited Aug 10, 2017 at 3:21 Cœur 38.8k25 gold badges205 silver badges277 bronze badges asked Sep 21, 2015 at 6:25 DhanaDhana 7233 gold badges14 silver badges41 bronze badges 2
  • Do you want it to alert after every first click..? – Rayon Commented Sep 21, 2015 at 6:31
  • The question is somewhat ambiguous. You want to track second click/each click after second click/each even click – Tushar Commented Sep 21, 2015 at 6:33
Add a ment  | 

4 Answers 4

Reset to default 7

Use counter instead..

var count = 0; //global variable
function showMessage() {
  if (count++ == 1) { //Compare and then increment counter
    alert("It's a second click message"); //this alert message will be shown only on second click of a button
  }
}
<input type="button" value="Message" onclick="showMessage()">

If you are not looking for the dbclick event, then you can use a flag to check whether it is the second click to show the alert

var flag;

function showMessage() {
  if (flag) {
    alert("It's a second click message"); // this alert message should be shown on second click of a button
  } else {
    flag = true;
  }
}
<input type="button" value="Message" onclick="showMessage()">

Consider this code, This is alert message after every alternate click:

var count = 1;

function showMessage() {
  if (!(count++ % 2))
    alert("It's a second click message"); //this alert message at every second click
}
<input type="button" value="Message" onclick="showMessage()" />

use ondblclick instead of onclick

Like below

<input type="button" value="Message" ondblclick="showMessage()">
发布评论

评论列表(0)

  1. 暂无评论