javascript - 为什么我的代码中函数的调用位置很重要?
问题描述
两个代码之间的唯一区别是我调用“de()”函数的地方。我留下了下面的 codepen 链接以准确了解问题所在。问题是,当我单击错误代码中的按钮时,它给了我相同的颜色,而不是不同的颜色,但是如果我按照正确的代码运行该函数,当我单击每个按钮时,它会给出不同的颜色。我在互联网上搜索但找不到答案。为什么会这样?它的工作代码:https ://codepen.io/BerkayAkgurgen/pen/wvoKPGM 它的问题代码: https ://codepen.io/BerkayAkgurgen/pen/rNWOYep
// it's working code
eventListener();
function de() {
const denemeArray = ["#f2f", "#000000", "#ff0"];
let be = Math.floor(Math.random() * denemeArray.length);
return denemeArray[be];
}
function eventListener() {
document.getElementById("deneme").addEventListener("click", function () {
const choice = de();
de();
document.body.style.backgroundColor = choice;
});
}
// it's problem code
eventListener();
function de() {
const denemeArray = ["#f2f", "#000000", "#ff0"];
let be = Math.floor(Math.random() * denemeArray.length);
return denemeArray[be];
}
function eventListener() {
const choice = de();
document.getElementById("deneme").addEventListener("click", function () {
de();
document.body.style.backgroundColor = choice;
});
}
解决方案
在问题代码中,变量“选择”的值仅设置一次。每次点击都会调用函数 de(),但不使用返回值。
function setEventListener() {
const ORIGINAL_COLOR = de();
document.getElementById("deneme").addEventListener("click", function actualEventListener() {
const THIS_COLOR_IS_NEVER_USED = de();
document.body.style.backgroundColor = ORIGINAL_COLOR;
});
}
推荐阅读
- java - Commons Configuration AbstractConfiguration 的 get() 和 getArray() 有什么问题?
- python - 在 Windows 上通过 pip 安装包“hpelm”时出现 Python 错误
- php - Laravel 项目链接在 heroku 上不起作用
- java - 在 Spring MVC 中无法从单独的服务包中找到 bean
- sql - 将 JSON 文件数据值转换为 SQL 表的行和列
- arrays - 在 Redux 中访问 promise 返回的数据
- ansible - Ansible - 在用户模块中使用 for 循环
- itext - 在重新打开的 PDF 文档的指定页面上使用“setFixedPosition”设置表格
- java - Jhipster 没有创建我在 jhipster 命令时导入的实体
- amazon-web-services - 在 S3 中创建前缀以并行读取并提高性能