How can I use a
in genTable
? It says that a is not defined
我怎样才能在genTable中使用?它说a没有定义
JS:
function colNum(){
a=prompt(' The number of columns?');
if(!parseInt(a))
{
console.log("Not number")
}
}
function genTable() {
table = document.createElement('table');
table.setAttribute('id','tbl');
tr = document.createElement('tr');
for (var i = 0; i < a; i++)
{
var th1 = document.createElement('th');
var text1 = document.createTextNode(i);
th1.appendChild(text1);
tr.appendChild(th1);
}
table.appendChild(tr);
document.body.appendChild(table);
}
HTML
<body onload='colNum()'>
1 个解决方案
#1
To use a
in genTable
, either
要在genTable中使用,要么
-
Give
genTable
a parameter and invoke with it fromcolNum
给genTable一个参数并从colNum中调用它
// in function colNum genTable(a); // a refers to the variable named a // ... function genTable(a) { // a refers to the parameter named a }
-
var a;
in a closure that contains bothcolNum
andgenTable
, and don'tvar
over it in a descendant closure (you're currently not usingvar
at all)var a;在包含colNum和genTable的闭包中,并且不要在后代闭包中对其进行变换(您当前根本不使用var)
var a; function colNum() { // ... } function genTable() { // ... }
Currently you can already access it, but this is because you've not var
d it, which is a bad habbit to get into as it can cause identifier conflicts in future code
目前你已经可以访问它,但这是因为你没有讨论它,这是一个不好的习惯,因为它可能导致未来代码中的标识符冲突
#1
To use a
in genTable
, either
要在genTable中使用,要么
-
Give
genTable
a parameter and invoke with it fromcolNum
给genTable一个参数并从colNum中调用它
// in function colNum genTable(a); // a refers to the variable named a // ... function genTable(a) { // a refers to the parameter named a }
-
var a;
in a closure that contains bothcolNum
andgenTable
, and don'tvar
over it in a descendant closure (you're currently not usingvar
at all)var a;在包含colNum和genTable的闭包中,并且不要在后代闭包中对其进行变换(您当前根本不使用var)
var a; function colNum() { // ... } function genTable() { // ... }
Currently you can already access it, but this is because you've not var
d it, which is a bad habbit to get into as it can cause identifier conflicts in future code
目前你已经可以访问它,但这是因为你没有讨论它,这是一个不好的习惯,因为它可能导致未来代码中的标识符冲突