繁体   English   中英

我如何使用此代码 consol.log countRight?

[英]How do i consol.log countRight with this code?

function rightAnswer() {
  console.log('right')
  var countRight = 0;
  [Button2, Buttonb3].forEach(a =>
    a.addEventListener('click', () => {
      countRight += 1;

    })
  );
}

我需要帮助才能打印consol.log(countRight) 到目前为止,当我使用该行代码时,consol 始终显示 countRight = 0 即使它应该根据用户输入显示 1 或 2。 我需要帮助才能使此代码正常工作。

如果我将consol.log(countRight)放在countRight += 1;之后,它不起作用

 function rightAnswer() { var countRight = 0; [Button2, Buttonb3].forEach(a => a.addEventListener('click', () => { countRight += 1; // this is where you should be able to log the value console.log(`right value is: ${countRight}`); }) ); }

这是意大利面条代码。 您的 function 通过引用“Button2”、“Buttonb3”来破坏 scope

如果您想登录点击,正确的登录位置是在点击处理程序中。

命名的含义是将调用countRight来增加计数——因为在调用countRight之前不会添加任何处理程序(并且应该只调用一次,因此不会添加多个处理程序)。

load事件上添加处理程序可能更有意义。 如果您真的打算在将来的任意时间添加它们,它当然可以放在一个方法中,再次注意它应该只被调用一次,或者在再次调用它之前删除事件侦听器。

 window.addEventListener('load', () => { let countRight = 0 const button1 = document.getElementById('button1') const button2 = document.getElementById('button2') const buttons = [button1, button2] const output = document.getElementById('output') buttons.forEach(b => { b.addEventListener('click', b => { countRight++ output.innerText = countRight console.log(`countRight = ${countRight}`) }) }) }, false);
 <button id="button1">Button #1</button> <button id="button2">Button #2</button> <div>Clicked <span id="output">0</span> times.</div>


切线

发布完整示例的原因是人们可以将其复制到他们的答案中并实际运行它。 这也是有意义的

暂无
暂无

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

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