I want to set a click event for each list like this:
Example 0. use an inline event handlers
<ul class="fruits">
<li class="apple" onclick="show(apple)">Apple</li>
<li class="orange" onclick="show(orange)">Orange</li>
<li class="cherry" onclick="show(cherry)">Cherry</li>
<li class="grape" onclick="show(grape)">Grape</li>
<li class="kiwi" onclick="show(kiwi)">Kiwi</li>
</ul>
As shown above, Inline event handlers, is simple and intuitive, but it's deprecated. so I will use addEventListener method. However, the latter is many different ways to write and I don't know the best.
Here are a few writing ideas I've come up with.
Example 1. Get the arguments value from class name or data-attribute.
const fruits = document.querySelectorAll(".fruits> li");
fruits.forEach((fruit) => {
fruit.addEventListener("click", function () {
// use the class name for matching with arguments. more option is data-attributes.
const fruitName = fruit.className;
show(fruitName);
});
});
Example 2. Get the arguments value from a list in JS.
const fruitList = ["apple", "orange", "cherry", "grape", "kiwi"];
for (let fruit of fruitList) {
let fruitElem = document.querySelector(`.fruits> li.${fruit}`);
fruitElem.addEventListener("click", function(){
show(fruit)
});
}
Example 3. Get the arguments value from a list, more complex than EX2 for future management, in JS.
const fruitList = [
{event: "click", key: "apple", func: show},
{event: "click", key: "orange", func: show},
{event: "click", key: "cherry", func: show},
{event: "click", key: "grape", func: show},
{event: "click", key: "kiwi", func: show},
]
for (let fruit of fruitList) {
let fruitElem = document.querySelector(`.fruits> li.${fruit.key}`);
fruitElem.addEventListener(fruit.event, function(){
fruit.func(fruit.key);
});
}
What I would like to ask is:
- Which is the best way to do this (EX0-3)?
- If it was you, how to implement this?
Please teach me.