按钮点击显示隐藏消息的JavaScript功能故障排查求助
问题排查:按钮点击无法触发显示消息
核心错误点
- 按钮点击事件传参错误:
onclick="hideUnhide(paragraph1)"中的paragraph1会被当作未定义变量处理,正确写法是传入字符串格式的ID值:onclick="hideUnhide('paragraph1')" - 初始显示逻辑不符合需求:目标段落默认处于显示状态,当前代码第一次点击会隐藏它,需要给段落添加初始样式
display: none,才能实现点击显示消息的效果
修复后的完整代码
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Greeting Page</title> <style> h1 { font-size: 14pt; text-align: center; } body { background-color: #eec0c8; font-family: Georgia; } button { background-color: rgb(245, 66, 132); padding: 33px; } button:hover { background-color: #ffffff; } #paragraph1 { display: none; /* 初始隐藏目标段落 */ } </style> </head> <body> <h1> Welcome to my page! </h1> <p>This is a simple webpage created as a learning exercise.</p> <p> <button onclick="hideUnhide('paragraph1')">Click to see a message!</button> </p> <p id="paragraph1">Welcome to the world of coding!</p> <script> function hideUnhide(id){ const p1 = document.getElementById(id); if (p1.style.display == "none"){ p1.style.display = "block"; } else { p1.style.display = "none"; } } </script> </body> </html>
内容的提问来源于stack exchange,提问作者mollyxxhunter
相关产品推荐
相关产品推荐

