I'm new to javascript and I'm trying to create a menu of buttons. In the menu, I want to add event listeners when I click a button. My problem is I'm not sure how to implement it, to make it possible to target each button with the specific code that button need to run.
I have a button that needs to turn red when clicked and another that needs to load another site. How is it possible to achieve these things.
At the moment I generate the Buttons from a JSON document and create them in the code you can see below.
EDIT: added id attribute to javascript
function createMenu(jsonObj) {
let menu = jsonObj["menuitems"];
console.log(menu[0]);
let table = document.createElement("table");
for (let i = 0; i < menu.length; i++) {
let tableSection = document.createElement("tr");
let tableItem = document.createElement("td");
tableSection.appendChild(tableItem);
let button = document.createElement("BUTTON");
tableItem.appendChild(button);
let text = document.createTextNode(menu[i].item);
button.appendChild(text);
button.classList.add("menuButtons");
table.appendChild(tableSection);
button.setAttribute("id", menu[i].id);
button.addEventListener("click",/*What do i write here*/);
}
document.getElementById("menuDiv").appendChild(table);
}
Standards advice to not declare variable in loop. You can make an attribute ( data-horsSujet ) and compare the value to know what to do. Like this :
function createMenu(jsonObj) {
const menu = jsonObj["menuitems"];
console.log(menu[0]);
const table = document.createElement("table");
const myfct = function (event) {
const button = event.target;
if (button.getAttribute("data-horsSujet") == 1)
button.style.color = "red";
else
document.location = "google.fr";
}
for (let i = 0, tableSection, tableItem, button, text; i < menu.length; i++) {
tableSection = document.createElement("tr");
tableItem = document.createElement("td");
tableSection.appendChild(tableItem);
button = document.createElement("BUTTON");
tableItem.appendChild(button);
text = document.createTextNode(menu[i].item);
button.appendChild(text);
button.classList.add("menuButtons");
table.appendChild(tableSection);
button.setAttribute("id", menu[i].id);
button.addEventListener("click", myfct);
button.setAttribute("data-horsSujet", i);
}
document.getElementById("menuDiv").appendChild(table);
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.