JavaScript作业:下拉菜单取值后按钮点击无响应报错咨询
问题原因
- DOM方法拼写错误:原生获取DOM元素的方法正确写法是
document.getElementById(),你代码中全部写成了document.getElementByID(最后一位d误写为大写D),不存在的方法调用会直接抛出异常,导致后续代码终止执行,因此按钮点击无响应。同时方法调用失败会返回null,给null绑定onclick事件就会触发你看到的「无法为null变量赋值」的报错。 - 下拉框取值逻辑错误:你先通过
document.getElementById('chore').value拿到了选中项的value字符串,后续又尝试从字符串读取target、options属性,字符串本身没有这类属性,会触发二次报错。 - 变量类型误用:你将选中项的文本字符串赋值给
chore变量后,又尝试读取chore.value,字符串不存在value属性,最终存入Map的值会是undefined,后续清空chore.value的操作也会报错。
修正后可运行代码
<!DOCTYPE html> <html> <head> <title>Camp Whack-a-Doo Chore List</title> </head> <body> <h1>Add to the Chore List</h1> <p>Enter the Camper's name and their assigned chore, then click the Add button. Click the Display button to view the list.</p> <label for = "name">Camper Name</label> <input type = "text" id = "name" /><br/> <label for = "chore">Choose a Chore</label> <select id = "chore"> <option value = "frontSweep">Front Room Sweep</option> <option value = "backSweep">Back Room Sweep</option> <option value = "outsideGrounds">Outside Grounds</option> <option value = "toilet">Clean Toilet</option> <option value = "sink">Clean Sink</option> <option value = "trashSupplies">Trash Patrol and Supplies</option> </select><br/> <button id = "btnToAddToCL">Add to Chore List</button> <button id = "btnToDisplayCL">Display Chore List</button> <div id = "result"></div> <script> const ADDBUTTON = document.getElementById('btnToAddToCL'); const DISPLAYBUTTON = document.getElementById('btnToDisplayCL'); let choreList = new Map(); ADDBUTTON.onclick = function(){ let nameInput = document.getElementById('name'); let choreSelect = document.getElementById('chore'); // 这里取选中项的展示文本存入Map,如果你要存value直接用choreSelect.value即可 let choreText = choreSelect.options[choreSelect.selectedIndex].text; choreList.set(nameInput.value, choreText); // 清空输入和选择 nameInput.value = ""; choreSelect.selectedIndex = 0; }; DISPLAYBUTTON.onclick = function(){ let out = ""; for(let x of choreList.entries()){ out += x[0] + ": " + x[1]; out += "<br/>"; } document.getElementById('result').innerHTML = out; } </script> </body> </html>
内容的提问来源于stack exchange,提问作者Kayla
相关产品推荐
相关产品推荐

