- 我通过 map 方法迭代了 fruits 数组,并在浏览器中显示了这些元素。
- 但是在每次点击水果时,我都需要分别显示水果名称a的相应提醒
- 但现在在我的点击中我只看到 a 而当我点击字母 b 时它应该是 b
- 我需要为每个字母附加事件处理程序吗
- 你能告诉我解决这个问题的最佳方法吗
- 在下面提供我的代码片段和沙箱。
function sampleFunction() {
let fruits = ["a", "b", "c", "d", "e", 'f', "g"];
var fruitsElement = document.getElementById('fruits1');
fruits.map(item => {
console.log("item--->", item);
fruitsElement.innerHTML += item
return item;
});
/* var fruitsElement = document.getElementById('fruits1');
for (var i = 0; i < fruits.length; i++) {
fruitsElement.innerHTML += fruits[i];
} */
}
function fruitsClick() {
alert("I am fruit a");
}
body {
background-color: #1d2126;
color: white;
}
<h1>Hello, World</h1>
<button onclick="sampleFunction()">test</button>
<h1 onclick="fruitsClick()" id="fruits1"> </h1>
最佳答案
为每个水果名称创建单独的 span。 fruitsClick()
然后可以检查您单击的是哪个跨度并获取其文本内容。
function sampleFunction() {
let fruits = ["a", "b", "c", "d", "e", 'f', "g"];
var fruitsElement = document.getElementById('fruits1');
fruits.forEach(item => {
console.log("item--->", item);
fruitsElement.innerHTML += `<span class="fruit">${item}</span>`;
});
}
function fruitsClick(e) {
e.stopPropagation(); // prevent bubbling from <span> to <h1>
let fruit = e.target.innerText;
alert("I am fruit " + fruit);
}
body {
background-color: #1d2126;
color: white;
}
<h1>Hello, World</h1>
<button onclick="sampleFunction()">test</button>
<h1 onclick="fruitsClick(event)" id="fruits1"> </h1>
关于javascript - 将事件处理程序附加到整个字母表或只是一个接一个,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58599422/