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