0

我试图使用 questionID 变量来跟踪一些问题和答案。但似乎每次我运行我的函数时变量都会丢失记忆?这就是我的想法。

当我要求:颜色,然后回答:粉色、紫色或绿色时,它会跳转到最后一个语句;else if(questionID == -1) 这不是我的意图。

我该如何解决这种行为?我在本地运行脚本。

var questionID = -1;

function askQ() {
    var findme = document.getElementById('askBox').value.toLowerCase();
    var dontUnderstand = new Array();
    dontUnderstand[0] = "Excuse me, What did You say ?";
    dontUnderstand[1] = "Sorry, I cant understand You now. ^_^";
    dontUnderstand[2] = "Sorry!, I got to go now... CU !";
    dontUnderstand[3] = "ohh... Can you repeat that one more time ?";
    var randomIndex = Math.round(Math.random() * 3);
    if (findme.match(/(age|old)/)) {
        document.getElementById('bubble').innerHTML = "ohh,, I am " +
            obj1.age + " years old, How old are You ?";
    }
    if (!isNaN(findme)) {
        document.getElementById('bubble').innerHTML = "ohh.. that's kinda old !";
    }
    if (findme.match(/(color)/)) {
        document.getElementById('bubble').innerHTML = "My favourite color " +
            " is Purple, What's yours ?";
        questionID = 6;
    }
    if (findme.match(/(pink|purple|green)/) && questionID == 6) {
        document.getElementById('bubble').innerHTML = "well...that's cute !!";
        questionID = -1;
    }
    if (findme.match(/(hi|hello)/)) {
        document.getElementById('bubble').innerHTML = "Hi there, nice to meet You !";
    } else if (questionID == -1) {
        document.getElementById('bubble').innerHTML = dontUnderstand[randomIndex];
    }
}
4

2 回答 2

1

我首先将它添加到函数的顶部和底部:

console.log('starting', questionID);


console.log('ending', questionID);

然后使用您的调试日志查看发生了什么......或者您可以添加一个手表并使用 firebug 或 chrome 逐步执行您的代码

还想知道为什么你不使用 jQuery ......

于 2013-11-07T11:20:37.660 回答
0
 if(findme.match(/(pink|purple|green)/) && questionID == 6){
              document.getElementById('bubble').innerHTML = "well...that's cute !!";
      // You're setting it to -1.
      questionID = -1;
  }

另外,为什么不通过创建函数questionID的属性来限制对全局对象的污染。askQ

askQ.questionID = 6

于 2013-11-07T11:18:58.747 回答