首页 > 解决方案 > 检查器中 DOM 中缺少类属性

问题描述

我正在使用一个函数来尝试选择一个具有类属性的 div,该属性嵌套在具有 ID 的 div 中。该函数什么都不做,经过一些调试后发现,当我在浏览器中检查元素时,即使我的 HTML 中有一个类,div 也没有显示一个类。因为没有类,所以函数不知道要选择什么。在下面的代码中看到函数 playBall 正在调用函数 countDown 应该选择 div.timer。

<!DOCTYPE html>
<html>
  <head>

    <title>Home Run Derby (CSCI2447)</title>
    
    <!-- CSS styles: This is for me to worry about; not you. -->
    <link href="css/game.css" rel="stylesheet" />
    
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
    
    <script>
        var secondsRemaining = 30;
        var score = 0;
        var gamerFirstName;
        $(document).ready(function(){
        gamerFirstName = prompt("Please enter your first name."," ");
            $('div#content p').text('Hello ' + gamerFirstName + '! Are you ready? After clicking "start", you will have 30 seconds to hit as many home runs as you can. The images appear randomly so be ready!');
       
            $('div#gamespace').html('<img src="img/baseball.png"/>');
            $('div.timer').removeClass('timer');
            alert(numberX());
            alert(numberY());
            $('button#start_button').click(playBall);
            tallyScore();
            $('button#start_button').css({"width": "80px","height":"40px","font-size":"18px","background-color":"#b66f42","color": "#253f38", "font-family":"baseball"});
        });
        function numberX(){
            return Math.floor(Math.random() * 636);
    
        };
        function numberY(){
            return Math.floor(Math.random() * 350);
    
        };
        function tallyScore(){
            score++;
            $('span#score').text( score + " pts");
        };
        function playBall(){ 
            countDown();
        };
        function countDown(){
            secondsRemaining--; 
            $("div.timer").text(secondsRemaining + " Seconds Left");
        };
      </script>
    
    
  </head>
  <body>

    <div id="content">
        <div id="contenta">

            <h1><span>Home Run Derby</span></h1>
        
            <p></p>
        
              <div id="controls">
                 <span id="score">0 pts</span>
                <button type="button" id="start_button">Start!</button>
              </div>
                <div class="timer">
                    30 Seconds Left
                </div>
            </div>
        

        
        <div id="gamespace">

            
            
        </div>
        
    </div>
  </body>
</html>
 

标签: htmljquery

解决方案


在您的document.ready函数中,您有以下行timer从 div 中删除类,因此当countDown函数执行时,它无法找到div.timer选择器。

只需删除此行:

$('div.timer').removeClass('timer');

推荐阅读