变量在函数后保持重置

时间:2018-03-06 13:44:32

标签: javascript html css

基本上,我正在尝试创建一个测验应用程序(好吧,不是真正的测验,基本上点击一个选项导致另一个问题设置完全适合该选项。)并且不介意我的愚蠢问题和答案放在那里 - 那些是占位符。

我得到的错误是每次调用renderQuestions()时pos变量似乎都会重置。

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>yo</title>
    <style>
        #test {
            background-color: red;
        }
    </style>
</head>
<body>
    <div id="test"></div>

    <script>
        var pos = 0;
        var questions = [
            ["What the fish?", "fish", "gun", "fcuk", "duck", "muck"],
            ["You selected fish", "damn"],
            ["You selected gun", "gun"]
        ]
        function _(x) {
            return document.getElementById(x);
        }
        function renderQuestions() {
            test = _("test");
            console.log(pos);
            question = questions[pos][0];
            test.innerHTML += question + "<br>";
            for(var i = 0; i < questions[pos].length - 1; i++) {
                test.innerHTML += "<input type='radio' name='choices' value='"+i+"'>" + questions[pos][i+1] + "<br>";
            }
            test.innerHTML += "<button onclick='processAnswer("+pos+")'>Submit</button>";
        }
        function processAnswer(pos) {
            if(pos == 0) {
                choices = document.getElementsByName("choices");
                for(var i = 0; i < choices.length; i++) {
                    if(choices[i].checked) {
                        choice = choices[i].value;
                    }
                }
                if(choice == "0") {
                    pos = 1;
                    console.log(pos);
                } else if(choice == "1") {
                    pos = 2;
                } else {
                    alert("No position set")
                }
                renderQuestions();
            } else {
                alert("Out of bounds")
            }
        }
        renderQuestions();
    </script>
</body>
</html>

以下是我在控制台中调试它时的样子: console

似乎在点击单选按钮后,它成功地将pos设置为1,但随后立即将其重置为0.为什么会这样?

1 个答案:

答案 0 :(得分:5)

如果您希望pos充当全局变量,请不要将其传递给您的processAnswer()函数,不要在该函数中使用参数pos

这是一个可变范围的问题。您目前只修改pos的本地副本,该副本不会更改pos函数中renderQuestions()的值。

相关问题