[英]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.