[英]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;
})
);
}
I need help with being able to print consol.log(countRight)
.我需要帮助才能打印
consol.log(countRight)
。 So far when i use that line of code the consol always shows countRight = 0 even though it should say either 1 or 2 depending on the users input.到目前为止,当我使用该行代码时,consol 始终显示 countRight = 0 即使它应该根据用户输入显示 1 或 2。 I need help with making this code work.
我需要帮助才能使此代码正常工作。
It does not work if i put consol.log(countRight)
after countRight += 1;
如果我将
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}`); }) ); }
This is spaghetti code though.这是意大利面条代码。 Your function breaks scope by referencing "Button2", "Buttonb3"
您的 function 通过引用“Button2”、“Buttonb3”来破坏 scope
If you want to log on clicks the right place to log is in the click handler.如果您想登录点击,正确的登录位置是在点击处理程序中。
The implication from naming is that countRight
will be called to increment the count–as it is no handlers will be added until countRight
has been called (and it should be called only once so multiple handlers aren't added).命名的含义是将调用
countRight
来增加计数——因为在调用countRight
之前不会添加任何处理程序(并且应该只调用一次,因此不会添加多个处理程序)。
It might make more sense to add the handlers on the load
event.在
load
事件上添加处理程序可能更有意义。 If you really mean to add them at an arbitrary time in the future it can certainly be put in a method, noting again it should only be called once, or the event listeners removed before calling it again.如果您真的打算在将来的任意时间添加它们,它当然可以放在一个方法中,再次注意它应该只被调用一次,或者在再次调用它之前删除事件侦听器。
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>
Tangential切线
The reason to post a complete example is so people can copy it into their answers and actually run it.发布完整示例的原因是人们可以将其复制到他们的答案中并实际运行它。 It also makes sense to
这也是有意义的
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.