我一直在使用javascript,html和css进行基本的乒乓球比赛,以获得编码体验。
我整夜搜索,研究和调试了我的代码,我很难过。我通过控制台日志发现我可以通过id访问div的子对象,但我无法使用parent.children / parent.children [0] / parent通过它的父对象访问相同的元素.childrenCount或任何东西。
我感兴趣的代码区域是.html文件中的第12-21行,.js文件中的第12和第58行。就像我提到的,我可以通过getElementById访问元素对象,但我无法通过它的父对象.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
}
}
}*/
答案 0 :(得分:0)
我认为在完成渲染之前,正在评估行var Popup = { ... }
。那时候,没有孩子,这就是你所处的状态。
将window.onload = function () { ... }
放在整个JS文件周围。或者执行上述评论中nnnnnn建议的内容,并将script
标记移至正文的底部。无论哪种方式都将确保在分配依赖于DOM元素的变量时DOM完全可用。