javascript - 只运行一次 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)
}
解决方案
您可以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>
推荐阅读
- snowflake-cloud-data-platform - 雪花函数如何输入IN语句来运行
- javascript - SQL 分配无限参数
- c++ - 字符串不会存储在链表中
- javascript - 如何在我的网页中垂直排列水平排列的部分,以使我的页面在设备上响应
- python - 如果在 1 秒内检测到声音 1,如果在输入后检测到 3 秒声音 2,则打印 python
- node.js - 在 Typescript 中,try...catch 错误对象显示“对象类型为‘未知’.ts(2571)”
- google-apps-script - 当用户编辑电子表格中的单元格时,是否有脚本函数可以获取用户电子邮件?
- node.js - 在 Postman 中调用 PATCH 失败
- c# - 如何编写此扩展方法以由 EF Core 转换为 SQL Server?
- pip - 下载pyqt5时出错..使用最新版本的pip和sip版本15.0.2(使用Mac Os Big Sur 11.5.2-apple Silicon)