[英]When I press the button it gives me one result and not all the Map results I have. I only get value 1
I need help.我需要帮助。
There's something in the code that's not working properly for me.代码中的某些内容对我来说无法正常工作。
When I press a button it pulls me value of value of one product and every other button just does not pull their figure.当我按下一个按钮时,它会拉动我一种产品的价值,而其他每个按钮都不会拉动它们的数字。
const itemadd = document.querySelectorAll('.item-this');
let currentAccount;
let proteinValue;
const foods = new Map([
['קוטג',23],
['ביצה',11],
['יוגורט Pro',20],
['טונה',23]
]);
foods.forEach(function (value, index, arr) {
const html = `<li class="">
<strong>${index}</strong> כמות חלבון ${(proteinValue =
value)}</li><button class="btn btn-primary item-this">הוסף</button><hr>`;
items.insertAdjacentHTML('afterbegin', html);
});
const itemadd = document.querySelectorAll('.item-this');
for (let i = 0; i < itemadd.length; i++)
itemadd[i].addEventListener('click', function () {
console.log(proteinValue);
});
When I press the button it only records the figure of ['tuna', 23] Intention 23 and all the other entries do not print them for me that I press the button当我按下按钮时,它只记录 ['tuna', 23] Intention 23 的数字,所有其他条目都不会为我打印它们,因为我按下了按钮
You can attach event handler to the button directly and pass the corresponding value.您可以直接将事件处理程序附加到按钮并传递相应的值。
let currentAccount={};
let proteinValue;
const foods = new Map([
['קוטג',23],
['ביצה',11],
['יוגורט Pro',20],
['טונה',23]
]);
foods.forEach(function(value,index,arr){
const html = `<li class=""> <button id="add" class="btn btn-primary" onclick="test(${value})" data-protein="${value}">הוסף</button>
<strong>${index}</strong> כמות חלבון ${proteinValue = value}</li><hr>`
items.insertAdjacentHTML('afterbegin', html);
})
function test(val){
console.log(val);
}
or with eventListener, you can use data attribute.或者使用 eventListener,您可以使用 data 属性。
let currentAccount={};
let proteinValue;
const foods = new Map([
['קוטג',23],
['ביצה',11],
['יוגורט Pro',20],
['טונה',23]
]);
foods.forEach(function(value,index,arr){
const html = `<li class=""> <button id="add" class="btn btn-primary" data-protein="${value}">הוסף</button>
<strong>${index}</strong> כמות חלבון ${proteinValue = value}</li><hr>`
items.insertAdjacentHTML('afterbegin', html);
})
document.querySelectorAll('.btn-primary').forEach((ele) => {
ele.addEventListener('click', function(e){
console.log(e.target.getAttribute('data-protein'))
})
})
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.