为什么这只是打印出”hello world” 9次,而不是添加onclick事件?

huangapple go评论64阅读模式
英文:

Why is this just printing out hello world 9 times instead of adding the event onclick?

问题

以下是代码的翻译部分:

let number1 = document.getElementById("number1");
let number2 = document.getElementById("number2");
let number3 = document.getElementById("number3");
let number4 = document.getElementById("number4");
let number5 = document.getElementById("number5");
let number6 = document.getElementById("number6");
let number7 = document.getElementById("number7");
let number8 = document.getElementById("number8");
let number9 = document.getElementById("number9");
let number0 = document.getElementById("number0");
const numbers_ = [number0, number1, number3, number4, number5, number6,
                  number7, number8, number9];

function myfunction() {
    console.log("hello world");
};

numbers_.forEach(num => {
    num.addEventListener("click", myfunction)
});

请注意,我已经将HTML实体(如")转换为正常的引号(" "),以使代码正确运行。

英文:
let number1 = document.getElementById("number1");
let number2 = document.getElementById("number2");
let number3 = document.getElementById("number3");
let number4 = document.getElementById("number4");
let number5 = document.getElementById("number5");
let number6 = document.getElementById("number6");
let number7 = document.getElementById("number7");
let number8 = document.getElementById("number8");
let number9 = document.getElementById("number9");
let number0 = document.getElementById("number0");
const numbers_ = [number0, number1, number3, number4, number5, number6,
              number7, number8, number9]
function myfunction() {
    console.log("hello world");
};

numbers_.forEach(num => {
    num.addEventListener("click", myfunction())
});

This is my code. It is just logging Hello World 9 times on load instead of waiting for the click. Please help.

答案1

得分: 6

因为你调用了一个函数而不是只传递它。
应该是:

numbers_.forEach(num => {
    num.addEventListener("click", myfunction)
});
英文:

Because you called a function instead of just pass it.
Should be:

numbers_.forEach(num => {
    num.addEventListener("click", myfunction)
});

huangapple
  • 本文由 发表于 2023年2月19日 23:55:44
  • 转载请务必保留本文链接:https://go.coder-hub.com/75501391.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定