如何添加eventlistener到菜单js?



我试图在单击菜单项时添加事件侦听器。

为什么是菜单。单击项时值未定义?

代码:

let menu = document.getElementById("myDropdown");
menu.addEventListener("click", generateMap);
function generateMap(event) {
if (menu.value == "all") {
console.log("all");
} else if (menu.value == "a1") {
console.log("a1");
} else if (menu.value == "a2") {
console.log("a2");
}
}
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">
<div class="dropdown">
<button onclick="myFunction()" class="dropbtn">Select Building</button>
<div id="myDropdown" class="dropdown-content">
<option value="all">All</option>
<option value="a1">A1</option>
<option value="a2">A2</option>
</div>
</div>

您没有使用正确的HTML结构。

<option>标签是<select>标签的子标签。

添加IDmyDropdown<select>标签,在select标签上,您可以附加事件侦听器

let menu = document.getElementById("myDropdown");
menu.addEventListener("click", generateMap);
function generateMap(event) {
if (menu.value == "all") {
console.log("all");
} else if (menu.value == "a1") {
console.log("a1");
} else if (menu.value == "a2") {
console.log("a2");
}
}
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">
<div class="dropdown">
<select id="myDropdown">
<option value="" selected disabled>Select Building</option>
<option value="all">All</option>
<option value="a1">A1</option>
<option value="a2">A2</option>
</select>
</div>

相关内容

  • 没有找到相关文章

最新更新