繁体   English   中英

如何使函数只运行一次JS

[英]How to make the function only runs once JS

如何使该功能每个按钮只运行一次? 如果单击“单击我”,则只能使用一次,其他按钮也一样。
为了不放置太多代码,我举了一个例子..: 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>

一种解决方案是注册已单击的按钮:

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

(另一种方法是使用实​​用程序库,如jQuery及其一个函数,但这仅是太过分了)

您可以将按钮元素引用发送到函数,然后从按钮中删除事件:

<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>

演示: http//jsfiddle.net/Guffa/CDjGY/

执行后,您可以使用空函数覆盖该函数

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

暂无
暂无

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

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