Reputation: 31
How can I use a
in genTable
? It says that a is not defined
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()'>
Upvotes: 1
Views: 59
Reputation: 66334
To use a
in genTable
, either
Give genTable
a parameter and invoke with it from 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 both colNum
and genTable
, and don't var
over it in a descendant closure (you're currently not using var
at all)
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
Upvotes: 1