javascript - 使用 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);
}
解决方案
好的,我已将您的代码更改为按预期工作
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>
推荐阅读
- javascript - React js - this.state 中的 API 响应是空对象
- ruby-on-rails - 如何使用 NPM、Webpacker 和 Rails 安装 Quill dev 2.0?
- android - Android Studio:缺少 Android 支持存储库
- json - 尝试使用 Devart dotConnect for Quickbooks 创建 Quickbooks 在线日记条目
- ms-access - 我试图在访问中的表达式生成器中执行“和”表达式,但它不起作用
- flutter - What is the functionality of .dart_tool folder in a Flutter application?
- r - 如何在不丢失原始变量的情况下离散化数值变量?
- makefile - 如何在 Makefile 的变量中运行命令?
- reactjs - 在没有 Javascript 的情况下反应路由
- python - 我有两个本地磁盘,我的 python 外部模块安装在我不使用的磁盘中