You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

按钮点击显示隐藏消息的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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.18 14:13:16