将计算变量从一个函数传递到另一个函数

时间:2011-03-09 10:37:19

标签: javascript variables

...不确定“计算”是正确的词......我写了两个函数,第二个函数需要输出第一个变量。我似乎无法通过......我的猜测是我说它错了,但似乎无法正确...可能与我盯着整个事情的时间有关..

我需要传递的变量是subset我试图在第二个函数的最后一行使用它。

如果重要,getPos函数将从输入框中获取其值。

javascript:

<script>
var alphabet = ["a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z"];

function getPos(value)
{
    var letterPosition = alphabet.indexOf(value);
    var subset = alphabet.slice(letterPosition+1, 26);
    document.getElementById('theRest').value = subset;
}

function appendTable(id)
{
    var tbody = document.getElementById(id).getElementsByTagName("tbody")[0];
    var i = 0;
    for (var r = 0; r < 4; r++) {
        var row = tbody.insertRow(r);
        for (var c = 0; c < 4; c++) {
            var cell = row.insertCell(c);
            cell.appendChild(document.createTextNode(subset[i++]));
        }
    }
}
</script>

1 个答案:

答案 0 :(得分:1)

<script>
var alphabet = ["a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z"];
var subset;

function getPos(value)
{
    var letterPosition = alphabet.indexOf(value);
    subset = alphabet.slice(letterPosition+1, 26);
    document.getElementById('theRest').value = subset;
}

function appendTable(id)
{
    var tbody = document.getElementById(id).getElementsByTagName("tbody")[0];
    var i = 0;
    for (var r = 0; r < 4; r++) {
        var row = tbody.insertRow(r);
        for (var c = 0; c < 4; c++) {
            var cell = row.insertCell(c);
            cell.appendChild(document.createTextNode(subset[i++]));
        }
    }
}
</script>

应该这样做。
在函数之前声明子集使其成为全局变量,如果在函数中使用var subset定义它,它将与该函数绑定,删除var使其使用全局变量。