heisenberg_wn 2022-11-23 14:38 采纳率: 100%
浏览 3
已结题

关于HTML和Javascript的初学者问题

初学者提问:为什么这个代码会报错?点击按钮没有反应?

代码:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>井字棋</title>
</head>
<body style = "background-color: #1f1f1f;">
    <h1 id = "tictactoeTitle1" style = "text-align: center; font-size: 224px; color: #dfdfdf; display: block; margin-top: 64px;">井字棋</h1>
    <button id = "tictactoeButton1" onclick = "startgameClick()" style = "text-align: center; font-size: 80px; border-radius: 16px; padding: 64px 144px; background-color: #dfdfdf; border: 0px; font-weight: bold; color: #3f3f3f; display: block; margin: 0 auto; margin-top: 256px;">开始</button>
</body>
<script>
    startgameClick = function () {
        var tictactoeTitle1Set = document.getElementById(tictactoeTitle1);
        tictactoeTitle1Set.style.display = "none";
    }
</script>
</html>

点击按钮之后就会这样报错:

Uncaught TypeError TypeError: Cannot read properties of null (reading 'style')
at startgameClick (e:\Programs HTML\Test\Test1-Tictactoe\tictactoe.html:16:28)
at onclick (e:\Programs HTML\Test\Test1-Tictactoe\tictactoe.html:11:280)

script放在了最后,为什么还是出问题?

  • 写回答

2条回答 默认 最新

  • 桑榆肖物 全栈领域新星创作者 2022-11-23 14:44
    关注

    需要加引号,document.getElementById("tictactoeTitle1");

    修改后这样:

    <html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title井字棋<title>
    <head>
    <body style = "background-color: #1f1f1f;">
        <h1 id = "tictactoeTitle1" style = "text-align: center; font-size: 224px; color: #dfdfdf; display: block; margin-top: 64px;">井字棋</h1>
        <button id = "tictactoeButton1" onclick = "startgameClick()" style = "text-align: center; font-size: 80px; border-radius: 16px; padding: 64px 144px; background-color: #dfdfdf; border: 0px; font-weight: bold; color: #3f3f3f; display: block; margin: 0 auto; margin-top: 256px;">开始</button>
    </body>
    <script>
        startgameClick = function () {
            var tictactoeTitle1Set = document.getElementById("tictactoeTitle1");
            tictactoeTitle1Set.style.display = "none";
        }
    </script>
    <html>
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

问题事件

  • 已结题 (查看结题原因) 11月23日
  • 已采纳回答 11月23日
  • 创建了问题 11月23日

悬赏问题

  • ¥20 西门子S7-Graph,S7-300,梯形图
  • ¥50 用易语言http 访问不了网页
  • ¥50 safari浏览器fetch提交数据后数据丢失问题
  • ¥15 matlab不知道怎么改,求解答!!
  • ¥15 永磁直线电机的电流环pi调不出来
  • ¥15 用stata实现聚类的代码
  • ¥15 请问paddlehub能支持移动端开发吗?在Android studio上该如何部署?
  • ¥20 docker里部署springboot项目,访问不到扬声器
  • ¥15 netty整合springboot之后自动重连失效
  • ¥15 悬赏!微信开发者工具报错,求帮改