簡體   English   中英

只運行一次 JavaScript 函數

[英]Only run JavaScript function once

單擊按鈕時,我將顯示圖像(在 JS 函數中),但是每次單擊按鈕時該函數都會打印圖像。 我希望該函數只運行一次,以便圖像只能顯示一次。 我需要在我的代碼中添加什么才能做到這一點?

<button class="colour-btn colour-btn--3" onClick="showImage3()"></button>
function showImage3() {
    var img3 = document.createElement('img')
    img3.setAttribute("src", "")
    img3.setAttribute("width", "700")
    img3.setAttribute("height", "400")
    document.body.appendChild(img3)
}

您可以使用Element.addEventListener與選項once設置為true

根據 MDN,選項once是:

一個布爾值,指示添加后最多應調用一次偵聽器。 如果為 true,則在調用時會自動刪除偵聽器。

<button class="colour-btn colour-btn--3"></button>
<script>
document.querySelector('button').addEventListener('click', showImage3, {once: true});
</script>

 function showImage3() { console.log("showImage3(); only called once"); var img3 = document.createElement('img'); img3.setAttribute("src", ""); img3.setAttribute("width", "700"); img3.setAttribute("height", "400"); document.body.appendChild(img3); } document.querySelector('button').addEventListener('click', showImage3, {once: true});
 <button class="colour-btn colour-btn--3">Show Image 3</button>

您還可以使用此實用程序once函數,該函數返回一個函數,該函數封裝了作為其參數傳入的函數,並且最多只運行一次。

function once(fn, context){
    if(typeof fn != "function") throw TypeError("fn is not a function");
    var ran = false, res;
    return function(){
        return ran ? res : (ran = true, res = fn.apply(context||this, Array.prototype.slice.call(arguments)));
    };
}

 function once(fn, context){ if(typeof fn != "function") throw TypeError("fn is not a function"); var ran = false, res; return function(){ return ran ? res : (ran = true, res = fn.apply(context||this, Array.prototype.slice.call(arguments))); }; } function showImage3() { console.log("showImage3(); only called once"); var img3 = document.createElement('img'); img3.setAttribute("src", ""); img3.setAttribute("width", "700"); img3.setAttribute("height", "400"); document.body.appendChild(img3); } var showImage3Once = once(showImage3);
 <button class="colour-btn colour-btn--3" onClick="showImage3Once();">Show Image 3</button>

var imageAdded = false

function showImage3() {
  if (!imageAdded) {
    var img3 = document.createElement('img')
    img3.setAttribute("src", "")
    img3.setAttribute("width", "700")
    img3.setAttribute("height", "400")
    document.body.appendChild(img3)
    imageAdded = true
  }
}

應該這樣做,假設您不介意在代碼中使用全局變量。 這不是最佳實踐,但它是快速解決此問題的最簡單方法。

您可以在第一次運行后重新定義該函數,使其僅運行一次。

function showImage3() {
    showImage3 = function() {};
    var img3 = document.createElement('img')
    img3.setAttribute("src", "")
    img3.setAttribute("width", "700")
    img3.setAttribute("height", "400")
    document.body.appendChild(img3)
}

暫無
暫無

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

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