HTML
<button class='button' data-next="games" data-parent="games1" data-storage="128" data-graphcard="2" data-processor="i3">Click here</button>Js。
let hardware = ["storage", "graphcard", "processor"];
const allButtonsToStore = document.querySelectorAll('.button');
allButtonsToStore.forEach((el, i) => {
el.addEventListener('click', () => {
hardware.forEach((item) => {
console.log(`${el.dataset.item}`);
});
});
});我要做的是从数组中获取每一项,并使用它在html中找到数据。
${el.dataset.*},其中‘*’=数组的项。
因此:获取数据集存储、图形卡和按钮处理器的值。这将是${el.dataset.storage},${el.dataset.graphcard}和${el.dataset.processor}。为了不写入数组的所有项,我尝试获取数组中的所有项(hardware.forEach((item))并放入${el.dataset.item}
但是由于.`${el.dataset.item}`.被"“包围,所以我无法在"${el.dataset.”之后转义,插入实际的item并再次捕获它,以便用}发送行
我尝试过像${el.dataset."item"}、${el.dataset.[item]}或${el.dataset.(item)}之类的东西,但没有成功。
发布于 2020-02-27 12:58:44
您几乎得到了正确的答案:语法正确的括号表示法是${el.dataset[item]}-i.e,没有dataset和[item]之间的额外.。见这里的概念证明:
let hardware = ["storage", "graphcard", "processor"];
const allButtonsToStore = document.querySelectorAll('.button');
allButtonsToStore.forEach((el, i) => {
el.addEventListener('click', () => {
hardware.forEach((item) => {
console.log(`${el.dataset[item]}`);
});
});
});<button class='button' data-next="games" data-parent="games1" data-storage="128" data-graphcard="2" data-processor="i3">Click here</button>
https://stackoverflow.com/questions/60433761
复制相似问题