html - 检查器中 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>
解决方案
在您的document.ready
函数中,您有以下行timer
从 div 中删除类,因此当countDown
函数执行时,它无法找到div.timer
选择器。
只需删除此行:
$('div.timer').removeClass('timer');
推荐阅读
- c++ - MIDI 通道消息之间是否有优先级?
- wordpress - 为什么我的 .htaccess 重定向在测试期间返回 200 而不是 301?
- python - 如何解决 OSError [Errno2] no such file or directory
- php - 在 2 个不同页面中发送的表单数据
- python - pymssql - 从ini文件到带有反斜杠问题的变量的服务器名称
- ruby-on-rails - Rails ActiveStorage 夹具附件 - 没有这样的文件或目录 @ rb_sysopen
- cassandra - Cassandra:如何自动删除旧记录以避免磁盘空间不足?
- javascript - 有没有办法向具有特定类的所有 html 元素添加函数
- arrays - xml 到 json 转换 ...字段名称未填充到输出 json 文件中
- python-3.x - 在二进制数组中找到转换(变化)点的有效方法