簡體   English   中英

如何使函數僅在javascript中運行一次

[英]How to make the function only runs once in javascript

如何使該功能每個按鈕只運行一次?
如果單擊“單擊我”僅一次,而其他按鈕也是如此,則為了不放置太多代碼,我舉了一個例子..:
http://jsbin.com/apexod/1/手表

<html>
<head>
<title></title>
</head>
<body>
<input type="button" value="click me" onclick="hello()"><br>
<input type="button" value="click me1" onclick="hello()"><br>
<input type="button" value="click me2" onclick="hello()">
<script>
   function hello(){
       alert("hello");
}
</script>
</body>
</html>

更改onclick處理程序,以便函數可以引用單擊的元素。

<input type="button" value="click me" onclick="hello.call(this)"><br>
<input type="button" value="click me1" onclick="hello.call(this)"><br>
<input type="button" value="click me2" onclick="hello.call(this)">

然后更改功能以刪除處理程序。

function hello(){
    alert("hello");
    this.onclick = null;
}

您只需刪除onclick

<html>
<head>
    <title></title>
</head>
<body>
    <input type="button" value="click" onclick="hello(this)"><br>
    <input type="button" value="click1" onclick="hello(this)"><br>
    <input type="button" value="click2" onclick="hello(this)">
<script>
       function hello(btn){ 
           alert("hello");
           btn.onclick = function(){};
    }
</script>
</body>
</html>

如果在腳本中添加事件偵聽器,則管理起來會更容易(考慮將行為與表示分開也是一種很好的做法):

演示: http//jsfiddle.net/4N4ur/

<input type="button" value="click">
<input type="button" value="click1">
<input type="button" value="click2">​

<script>
var inputs = document.getElementsByTagName('input');
for(var i=0; i<inputs.length; i++) {
    inputs[i].onclick = function() {
        hello();
        this.onclick = null; // reset the handler
    }
}
function hello() {
    alert('hello';
}
</script>

單擊按鈕后,調用下面的函數,其按鈕ID或名稱為param

    <script>
       function hello(caller){
          if (caller == 'button1' && $("#button1clicked").val() != '1')
          {
         // Your code to execute for the function
         alert("hello");
       // set value for button1clicked
       $("#button1clicked").val("1");
       }else {
       // do nothing
       }

     }
     </script>

將上述條件添加到沒有按鈕的位置

盡管上述情況和答案都是非常特定於單擊處理程序的,但有關how to make a function that only runs once的原始問題的答案通常是使用包裝函數完成的,類似於.once方法:

function once(fn) {
  var called = false;
  return function() {
    if (!called) {
      called = true;
      fn.apply(this, arguments);
    }
  }
}

上面的實現只允許原始函數被調用一次,並且將通過以后調用的上下文和參數。 然后將其用作:

var oneTimeFn = once(function() {
  console.log('I was called.');
});

oneTimeFn();
//-> I was called.

oneTimeFn();
//-> undefined

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM