javascript 如何获取按钮被按下的数值?

o2gm4chl  于 12个月前  发布在  Java
关注(0)|答案(1)|浏览(80)

我如何获得btns事件的值,它目前在开发日志中打印为<button>8</button>,我试图让它打印值8。

//create number array
const Numbers = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, "+", "-", "/", ".", "="];

const btnContainer = document.querySelector(".button-container");

//loop into button array
for (let i = 0; i < Numbers.length; i++) {
  //create button elements in for loop
  const button = document.createElement("button");

  button.innerText = Numbers[i];

  //render buttons to DOM at button-container
  for (let j = 0; j < Numbers.length; j++) {
    btnContainer.appendChild(button);
  }
}

const btn = document.querySelectorAll("button");
console.log(btn);

//loop through array usin for of
const screen = document.querySelector(".input-screen");

for (const btns of btn) {
  //press button by index
  btns.addEventListener("click", (num) => {
    const numValue = num.target.innerText;
    console.log(numValue);
  });
}

个字符

lp0sw83n

lp0sw83n1#

试试这个:

const btn = document.querySelectorAll("button");
console.log(btn);

const screen = document.querySelector(".input-screen");

for (const btns of btn) {
  btns.addEventListener("click", (num) => {
    const numValue = num.target.textContent; // or num.target.innerText
    console.log(numValue); // This will print the text inside the button, like '8'
  });
}

字符串

相关问题