简体   繁体   English

Javascript 计算器加位数

[英]Javascript Calculator adding digits

let numberButtons = document.querySelectorAll('[data-number]')
 let display = document.querySelector('[data-current-operand]')
 display.innerHTML = '';
 
 
numberButtons.forEach(button => {
  button.addEventListener('click', () => {
    console.log(button.innerHTML);
   display.innerHTML = button.innerHTML;
})

how do I make the code as such that when I click a button once and then do it again, it returns me 33 instead of just 3. Explanations are appreciated我如何制作这样的代码,以便当我单击一个按钮然后再次执行此操作时,它返回我 33 而不仅仅是 3。感谢解释

Please try this请试试这个

 const numberButtons = document.querySelectorAll('[data-number]') const display = document.querySelector('[data-current-operand]') display.innerHTML = ''; numberButtons.forEach(button => { button.addEventListener('click', (e) => { e.target.innerHTML += e.target.innerHTMl; })
Explanations: e.target gives you a reference to an instance of just clicked btn, and inner HTMl - I thinkyou already know what it is - gives you text inside button tag. 说明: e.target 为您提供了对刚刚单击的 btn 实例的引用,以及内部 HTMl - 我想您已经知道它是什么 - 在按钮标签内为您提供文本。 And += is how I call it "lazy incrementation" operator: it will do the actions like these; 而 += 就是我所说的“惰性增量”运算符:它将执行这些操作; let i = 9; 让我 = 9; i+=2 // === i = i + 2 i+=2 // === i = i + 2

here is one way to handle this:这是处理此问题的一种方法:

let numberButtons = document.querySelectorAll('[data-number]')
 let display = document.querySelector('[data-current-operand]')
 display.innerHTML = '';
 
 
numberButtons.forEach(button => {
  button.addEventListener('click', () => {
    display.innerText = display.innerText + button.innerText
    console.log(button.innerHTML)
})

Store the no of times the button is clicked in a variable say 'count'.将按钮被单击的次数存储在变量“count”中。

'3'.repeat(count)

The above code repeats the string 3 'count' no of times.上面的代码重复字符串 3 'count' 的次数。

If you have multiple buttons I suggest saving the count in an array如果您有多个按钮,我建议将计数保存在数组中

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

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