首页 > 解决方案 > 使用 onclick 函数从 forLoop 元素获取属性

问题描述

我还想通过使用带有“onclick”属性的 getAttribute 来获取 forLoop 元素的值。但我得到的已经是最终价值。您如何在单击的确切值元素上获得每个循环的值?这是我的代码;

const btn = document.createElement('button');
const scrOutput = document.createElement('p');
const numbers = ['0','1','2','3','4','5','6','7','8','9'];

// For Loop Condition
for (let i=0; i<numbers.length; i++) {
  btn.setAttribute('onclick', 'showOutput()');
  btn.setAttribute('value', numbers[i]);
  btn.innerText = numbers[i];
  document.getElementById('numbers').innerHTML += btn.outerHTML;
  const x = btn.getAttribute('value', numbers[i]);
  console.log(x);  
}

function showOutput(){
  const btnVal = btn.getAttribute('value');
  scrOutput.innerText = btnVal;
  document.getElementById('screen').innerHTML = scrOutput.outerHTML;
  console.log(btnVal);
}

标签: javascriptarraysgetattribute

解决方案


好的,我已将您的代码更改为按预期工作

const btn = document.createElement('button');
const scrOutput = document.createElement('p');
const numbers = ['0','1','2','3','4','5','6','7','8','9'];

// For Loop Condition
for (let i=0; i<numbers.length; i++) {
  // by adding `this` as an argument you make sure to pass the clicked button to the code inside the listener
  btn.setAttribute('onclick', 'showOutput(this)');
  btn.setAttribute('value', numbers[i]);
  btn.innerText = numbers[i];
  document.getElementById('numbers').innerHTML += btn.outerHTML;
  const x = btn.getAttribute('value', numbers[i]);
  console.log(x);  
}

function showOutput(element) {
  // here the element is given on each click
  const btnVal = element.value;
  scrOutput.innerText = btnVal;
  document.getElementById('screen').innerHTML = scrOutput.outerHTML;
  console.log(btnVal);
}
<div id="numbers"></div>
<div id="screen"></div>

这是一个干净的代码,可以满足您的要求

const numbersElement = document.querySelector("#numbers"),
  screenElement = document.querySelector("#screen"),
  numbers = ['0','1','2','3','4','5','6','7','8','9'];
// looping over numbers array and create a new button and add it to numbers element
numbers.forEach(function(number) {
  numbersElement.innerHTML += `<button value="${number}">${number}</button>`;
});
// using event delegation instead of looping over the buttons
numbersElement.onclick = function(e) {
  if(e.target.nodeName === "BUTTON") {
    screenElement.innerHTML = e.target.value;
  }
};
<div id="numbers"></div>
<div id="screen"></div>


推荐阅读