我一直在使用 javascript、html 和 css 开发一个基本的乒乓球游戏,以获得编码经验。
我整晚都在搜索、研究和调试我的代码,但我很困惑。我通过控制台日志发现我可以通过 id 访问 div 的子对象,但是我无法使用 parent.children/parent.children[0]/parent.childrenCount 或任何东西通过它的父对象访问相同的元素。
我感兴趣的代码区域是 .html 文件中的第 12-21 行,以及 .js 文件中的第 12 和 58 行。正如我提到的,我可以通过 getElementById 访问元素对象,但我不能通过它的父对象的 object.children 属性访问它。
<html>
<head>
<title>Stupid Pong</title>
<link rel="stylesheet" type="text/css" href="Stupid Pong.css">
<script src="Stupid Pong.js"></script>
</head>
<body id="GameAssets">
<div id="CanvasFrame">
<h1 id="Title">Stupid Pong</h1>
<div id="Popup">
<div id="PopupMessage">
Winning score
</div>
<input type="text" class="getText">
<button onclick="Ok()">Set</button>
<button onclick="Ok()">Play</button>
<button onclick="Ok()">Controls</button>
<button onclick="Ok()">Settings</button>
</div>
<canvas id="Game_Feild" width="640" height="480">
This browser isn't hip enough to render Stupid Pong.
</canvas>
</div>
</body>
// Canvas Variables
var GameCanvas;
var CanvasFrame;
var DrawKit;
// Game settings
var WinningScore;
var Difficulty;
var FPS;
// Input
var Popup = {
pframe: document.getElementById('Popup'),
messageBox: document.getElementById('PopupMessage')
};/*
var Button = [
document.getElementById('Popup').children[2],
document.getElementById('Popup').children[3],
document.getElementById('Popup').children[4],
document.getElementById('Popup').children[5]
];
*/
// New Ball
function createBall(x, y, r){
this.x = x;
this.y = y;
this.r = r;
this.draw = function(){
DrawKit.fillStyle = 'white';
DrawKit.beginPath();
DrawKit.arc(ballX, ballY, ballRadius, 0, Math.PI*2, true);
DrawKit.fill();
}
}
// New Paddle
function createPaddle(x, y, width, height){
this.x = x;
this.y = y;
this.width = width;
this.height = height;
this.draw = function(){
DrawKit.fillStyle = white;
DrawKit.fillRect(this.x, this.y, this.width, this.height);
}
}
// Load Canvas
window.onload = function(){
// Canvas Assets
GameCanvas = document.getElementById('Game_Feild');
CanvasFrame = document.getElementById('CanvasFrame');
DrawKit = GameCanvas.getContext('2d');
console.log(typeof Popup);
console.log(typeof Popup.pframe);
console.log(typeof Popup.messageBox);
console.log(typeof Popup.pframe.children);
// ...
for(var i = 3; i < 6; i++){
//console.log(typeof Popup.children[i]);
//Button[i].style.display = 'none';
}
}
// Manual Settings
/*
var SetWinningScore = function{
var entry = Popup.messageBox.children[1].value
Button[0].Ok = function{
if(typeof entry == 'number'){
}
else{
Popup.messageBox.children[0].value = "The \"winning score\" variable is" +
"a number. In other words, how many points
}
}
}*/
最佳答案
我认为 var Popup = { ... }
行是在 DOM 渲染完成之前被评估的。所以那个时候,没有 child ,这就是你坚持的状态。
将 window.onload = function () { ... }
放在整个 JS 文件周围。或者做什么nnnnnn建议在上面的评论中将 script
标记移动到正文的底部。无论哪种方式都将确保在分配依赖于 DOM 元素的变量时 DOM 完全可用。
关于javascript - 未捕获的类型错误 : Cannot read property 'children' of null(…) (no matter what I do),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40798804/