[英]simple javascript appendChild doesn't work
I'm new to web programming. 我是Web编程的新手。 I have tried to draw a table row with JavaScript but it's not working and I don't' know why.
我试图用JavaScript绘制表格行,但是它行不通,我也不知道为什么。
here's the code 这是代码
<div id="gameDiv"> </div>
<script type="text/javascript">
public function drawGame(){
var table = document.createElement('table');
table.setAttribute('style','float:left');
var startRow = table.insertRow(0);
var c = 'A'
for (j=0; j<8; j++) {
var text = document.createTextNode(c++);
var cell = startRow.insertCell(j);
cell.appendChild(text);
}
document.getElementById("gameDiv").appendChild(table);
}
$(document).ready(function() {
drawGame();
};
</script>
The problem is the fact you use public
. 问题是您使用
public
的事实。 Javascript doesn't have public
or private
, so putting that in front of your function declaration will cause errors. Javascript没有
public
或private
,因此将其放在函数声明的前面会导致错误。 If you open up your console, you'll see an error like: 如果打开控制台,将看到类似以下的错误:
SyntaxError: Unexpected token function
So to fix this, simply remove the private
modifier from your code. 因此,要解决此问题,只需从代码中删除
private
修饰符即可。
Also, you seem to be missing a closing parenthesis at the end of your code. 另外,您似乎在代码末尾缺少右括号。 Instead, you should use this:
相反,您应该使用以下代码:
$(document).ready(function() {
drawGame();
});
but that code could also be written much shorter: 但是该代码也可以写得更短:
$(drawGame);
Well, you're getting an error because I think you might be getting your languages mixed up, there's no need to declare a function as public in javascript, it will give you an error. 好吧,您遇到了错误,因为我认为您可能会混用各种语言,无需在javascript中将函数声明为public,这会给您带来错误。
The drawGame function can just be: drawGame函数可以是:
function drawGame(){
var table = document.createElement('table');
table.setAttribute('style','float:left');
var startRow = table.insertRow(0);
var c = 'A'
for(j=0; j<8; j++){
var text = document.createTextNode(c++);
var cell = startRow.insertCell(j);
cell.appendChild(text);
}
}
这是一种工作变体http://jsbin.com/hisewamu/4/edit ,“ $”概念是jquery的一部分,您应该包括
This should get rid of that NaN (Not a Number) nonsense. 这应该摆脱NaN(不是数字)的废话。
<script>
function drawGame(){
var table = document.createElement('table');
table.setAttribute('style','float:left');
var startRow = table.insertRow(0);
var c = 'A'.charCodeAt()
for(j=0; j<8; j++){
var text = document.createTextNode(String.fromCharCode(c++));
var cell = startRow.insertCell(j);
cell.appendChild(text);
}
document.getElementById("gameDiv").appendChild(table);
}
$(document).ready(function() {
drawGame();
});
</script>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.