首页 > 解决方案 > 只运行一次 JavaScript 函数

问题描述

单击按钮时,我正在显示图像(在 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)
}

标签: javascript

解决方案


您可以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>


推荐阅读