HTML按钮无法调用函数问题排查求助
问题解决:点击按钮显示隐藏内容失效
问题根源及修复点:
- 按钮事件属性拼写错误:所有按钮的
onlclick是笔误,正确写法是onclick,这是函数无法触发的核心原因。 - 元素集合操作错误:
document.querySelectorAll()返回的是多个元素的集合(NodeList),不能直接通过.style修改样式,必须遍历每个元素单独设置。 - 命名冲突:
etymology函数和同名类.etymology可能引发冲突,建议修改函数名避免混淆。 - 调试日志笔误:
console.log("cliced")里的拼写错误改为clicked,便于调试时确认函数执行状态。
修正后的完整代码:
<style> .card { font-family: Comic Sans MS; /* Kid font */ font-size: 20px; text-align: center; color: black; background-color: white; } li { text-align:left; display:none; } button{ display:block; width:28%; padding:auto; margin:auto; } .mono{ font-family:"Courier New"; font-size: 1.18em; font-weight:bold; width:50%; margin: auto; } .etymology { margin:auto; margin: 0 0 1em 0; display:none; } .info{ margin: 0 0 1em 0; display:none; } </style> {{FrontSide}} <!-- all tags with braces are anki tags --> <hr id=answer> <h2>{{def}}</h2> <button onclick="synonyms()"> Common Syn.</button> <ul> <li>{{c1}}, </li><li>{{c2}}, </li><li>{{c3}}, </li><li>{{c4}}, </li><li>{{c5}}</li> </ul> <div class="mono"> <div class="smol_details"> <div class="etymology">{{etymology}}<br> "{{source_language}}"</div> <button onclick="showEtymology()">Language info </button> <div class="info">{{usage_cat}} {{recognition}} {{book}} <br>{{commentary}}</div> <button onclick="showInfo()"> data data</button> </div> </div> <script> function synonyms() { document.querySelectorAll("li").forEach(item => { item.style.display = "inline"; }); console.log("clicked"); } function showEtymology() { document.querySelectorAll(".etymology").forEach(item => { item.style.display = "inline"; }); console.log("clicked"); } function showInfo() { document.querySelectorAll(".info").forEach(item => { item.style.display = "inline"; }); console.log("clicked"); } </script>
内容的提问来源于stack exchange,提问作者awesomeinator
相关产品推荐
相关产品推荐

