如何使用其他函数变量?

How can I use other function variables?

如何在 genTable 中使用 a?它说 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()'>

要在 genTable 中使用 a

  1. genTable一个参数并从colNum

    调用它
    // in function colNum
        genTable(a); // a refers to the variable named a
    // ...
    
    function genTable(a) {
        // a refers to the parameter named a
    }
    
  2. var a; 在包含 colNumgenTable 的闭包中,不要在后代闭包中 var 覆盖它(你目前根本没有使用 var)

    var a;
    function colNum() {
        // ...
    }
    function genTable() {
        // ...
    }
    

目前您已经可以访问它,但这是因为您还没有 vard 它,这是一个不好的习惯,因为它可能会导致未来代码中的标识符冲突