简体   繁体   中英

How to make the function only runs once JS

How to make the function only runs once per button? if clicks in "click me" only works once, and the same for the other buttons.
Order not to put much code, I put an example..: http://jsbin.com/apexod/2/edit

<input type="button" value="click me" onclick="hello('Jhon')"><br>
<input type="button" value="click me1" onclick="hello('Gerard')"><br>
<input type="button" value="click me2" onclick="hello('Kaoru')">
<script>
function hello(id){
    alert("hello "+id);
}
</script>

A solution would be to register what buttons have been clicked :

<script>
var done = {}
function hello(id){
   if (done[id]) return;
   done[id] = 1; 
   alert("hello "+id);
}
</script>

(another one would be to use a utility lib like jQuery and its one function but this would be overkill for just that)

You can send the button element reference along to the function, and remove the event from the button:

<input type="button" value="click me" onclick="hello(this,'Jhon')"><br>
<input type="button" value="click me1" onclick="hello(this,'Gerard')"><br>
<input type="button" value="click me2" onclick="hello(this,'Kaoru')">
<script>
function hello(el, id){
    alert("hello " + id);
    el.onclick = null;
}
</script>

Demo: http://jsfiddle.net/Guffa/CDjGY/

Once executed you can override the function with an empty function

function hello(){
     alert("hello " + id);
     hello = function(){}
}

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