我怎样才能使用其他函数变量?

时间:2022-06-09 22:51:34

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中使用,要么

  1. Give genTable a parameter and invoke with it from colNum

    给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; 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;在包含colNum和genTable的闭包中,并且不要在后代闭包中对其进行变换(您当前根本不使用var)

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

Currently you can already access it, but this is because you've not vard 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中使用,要么

  1. Give genTable a parameter and invoke with it from colNum

    给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; 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;在包含colNum和genTable的闭包中,并且不要在后代闭包中对其进行变换(您当前根本不使用var)

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

Currently you can already access it, but this is because you've not vard it, which is a bad habbit to get into as it can cause identifier conflicts in future code

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