如何运行在不同函数中定义的代码

时间:2017-10-21 02:25:20

标签: javascript arrays function

我有一些代码在页面加载时从数组生成随机值。

window.onload = startGame;

    function startGame() {
        document.getElementById("startGame").onclick = startHangman;
        document.getElementById("checkLetter").onclick = checkLetter;
        var hangmanWord = "";
        var words = ["APPLE", "COMPUTER", "BEDSHEET", "CASTE", "WATER", "LANTERN", "COFFE", "PROGRAMMER", "PILLOW", "CHEDDARCHIPOTLE POTETGULL"];
        var hangmanWord = words[Math.floor(Math.random() * words.length)];
            console.log(hangmanWord);
    }

我还有一个函数,用于检查输入值是否包含在页面加载时生成的随机值中。

function checkLetter() {

        var letter = document.getElementById("letter").value.toUpperCase();

        for (var i = 0; i < hangmanWord.length; i++) {
            if (hangmanWord[i] === letter) {
                console.log(hangmanWord[i]);
                var printLetter = document.createElement("p");
                var displayLetter = document.createTextNode(letter);
                printLetter.appendChild(displayLetter);
                document.getElementById("printLetter").appendChild(displayLetter);
            }
        }

我怎样才能做到这一点?我是否必须使用某种函数参数?

1 个答案:

答案 0 :(得分:0)

让hangman成为一个全局变量,即改变

window.onload = startGame;

function startGame() {
    document.getElementById("startGame").onclick = startHangman;
    document.getElementById("checkLetter").onclick = checkLetter;
    var hangmanWord = "";
    var words = ["APPLE", "COMPUTER", "BEDSHEET", "CASTE", "WATER", "LANTERN", "COFFE", "PROGRAMMER", "PILLOW", "CHEDDARCHIPOTLE POTETGULL"];
    var hangmanWord = words[Math.floor(Math.random() * words.length)];
        console.log(hangmanWord);
}

var hangmanWord = "";
window.onload = startGame;

function startGame() {
    document.getElementById("startGame").onclick = startHangman;
    document.getElementById("checkLetter").onclick = checkLetter;
    var words = ["APPLE", "COMPUTER", "BEDSHEET", "CASTE", "WATER", "LANTERN", "COFFE", "PROGRAMMER", "PILLOW", "CHEDDARCHIPOTLE POTETGULL"];
    hangmanWord = words[Math.floor(Math.random() * words.length)];
        console.log(hangmanWord); // globa;
}