调用数 组的JavaScript事件监听器

问题描述 投票:0回答:1

[我创建了一个图像地图,在其中单击特定区域时,我需要编写一个JavaScript函数,该函数提取6个字符串的数组并将它们放入列表中。

因此,例如,您单击蛋糕,我会给您配料表。

所以我正在处理这个:

document.querySelector('#cakeFrosting').addEventListener('click', (e) => {
  e.preventDefault();
  console.log(e.target);
  listElements();
});

我是否只将数组放入列表元素函数中?

javascript arrays event-listener eventhandler
1个回答
0
投票

如何使用属性或原型为每个“蛋糕”提供特定列表?我的意思是这样的:

<image id="cake1" class="cakes" src="path/to/cake.png" alt="cake1" />
<image id="cake2" class="cakes" src="path/to/cake2.png" alt="cake2" />

// At first, we store these DOM elements as variables
let cake1 = document.querySelector("#cake1");
let cake2 = document.querySelector("#cake2");

// And now, we can give them custom properties (because they are objects)
cake1["ingredients"] = ["Foo", "Bar"]; // or we can store them with prototype attribute (__proto__)
cake2["indredients"] = ["X", "Z"];
// And now we can write the listener for the all "cake"-class objects:
document.querySelectorAll('.cakes').forEach(cake => {
    cake.addEventListener("click",  () => {
       console.log(cake.ingredients);
       // Your cool stuff here
});
© www.soinside.com 2019 - 2024. All rights reserved.