简体   繁体   中英

call javascript function only once inside if statment

In this if statement I can call a function to alert a message if the statement are true but the problem I get the message more that one time every time I click on ok button on the message box I get the same message box, again and again, I want to get the message only one time (I want to call the function only one time in the if statement ) are there any way for that ?

My if statement loop

if(brd_side == COLOURS.WHITE) {
     firstmassege();
} else {
     secondmassege();
}

My functions :

function firstmassege() {
    alert('the first massege');
}

function secondmassege() {
    alert('the second massege');
}

How about using a flag to store the status. Please see the code below.

 $('#btn').click(firstmessage) var clicked = false; function firstmessage() { console.log('other statements...') if(!clicked){ alert('the first massege'); } clicked = true; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <button id="btn">click</button> 

In your case it will be like below

var flag =false;
    if (!flag){

     firstmessage();
     flag = true;

    }

This Code should simply work. Hope this would be useful. This displays the first message only once and the second message after the button is clicked for the second time as required.

<!DOCTYPE html>
<html>
<body>

<p>Click the button to test the Function</p>

<button onclick="myFunction()">Click </button>

<p id="demo"></p>

<script>

var executed = false;

function myFunction() {


if (!executed){

 firstmessage();
 executed = true;

} else {
  secondmessage();

}
}


function firstmessage() {
       alert('the first message');

}

     function secondmessage() {
            alert('the second message');

}
</script>

</body>
</html>

您可以在jquery中使用one

$('#myButton').one('click', function(){ alert('Hi!');});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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