首页 > 解决方案 > 为什么我的代码中函数的调用位置很重要?

问题描述

两个代码之间的唯一区别是我调用“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;
    });
}

标签: javascript

解决方案


在问题代码中,变量“选择”的值仅设置一次。每次点击都会调用函数 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;
});
}

推荐阅读