简体   繁体   English

为什么我的代码中函数的调用位置很重要?

[英]Why is the calling place of functions in my code important?

The only difference between the two codes is where I call the "de ()" function.两个代码之间的唯一区别是我将“de()”称为 function。 I left the codepen links below to understand exactly what the problem is.我留下了下面的 codepen 链接以准确了解问题所在。 The problem is that when I click the button in the faulty code, it gives me the same color, not the different color, but if I run the function as in the correct code, it gives a different color when I click on each button.问题是,当我单击错误代码中的按钮时,它给了我相同的颜色,而不是不同的颜色,但是如果我按照正确的代码运行 function,当我单击每个按钮时,它会给出不同的颜色。 I searched on the internet but couldn't find an answer.我在互联网上搜索但找不到答案。 Why is this happening?为什么会这样? it's working code: https://codepen.io/BerkayAkgurgen/pen/wvoKPGM it's problem code: https://codepen.io/BerkayAkgurgen/pen/rNWOYep它的工作代码: 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;
    });
}

In the problem code, the value to variable 'choice' is set only once.在问题代码中,变量“选择”的值仅设置一次。 The function de() is called on every click, but the return value is not used.每次点击都会调用 function 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;
});
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM