[英]addEventListener to all buttons using forEach
I am trying to addEventListener
to all of my buttons.我正在尝试将addEventListener
添加到我的所有按钮中。 This is my first time using addEventListener
and it is not running the usergetNumber
function which should display a random number when any button is clicked.这是我第一次使用addEventListener
并且它没有运行usergetNumber
function 当单击任何按钮时应该显示一个随机数。
const btns = document.querySelectorAll(".button");
btns.forEach(function(i) {
i.addEventListener('click', usergetNumber(){
});
function usergetNumber(){
const userRanNum = Math.floor(Math.random() * 10)
userscore_div.innerHTML = "You have " + userRanNum + " points";
computergetNumber();
function computergetNumber(){
const compRanNum = Math.floor(Math.random() * 10)
computerscore_div.innerHTML = "You have " + compRanNum + " points";
}
What am I doing wrong?
From top to bottom.从上到下。
usergetNumber() {... }
declaration in addEventListener()
. addEventListener()
中已经有一个 function usergetNumber() {... }
声明。 It's a function declaration not a callback here.这是一个 function 声明,而不是这里的回调。 Ref: Event Listener Callbacks .参考: 事件侦听器回调。usergetNumber() {...
is missing so therefore it isn't declared. usergetNumber() {...
上的右括号丢失,因此未声明。 Here's a basic example.这是一个基本的例子。 You can also just return
and not console.log
.您也可以只return
而不是console.log
。 Here, I'm just trying to duplicate the logic.在这里,我只是想复制逻辑。
const btn = document.querySelectorAll('button');
function getRandomNum() {
let randomNum = Math.random();
console.log(randomNum);
}
btn.forEach(function(button) {
button.addEventListener('click', getRandomNum);
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.