我开始使用javascript学习编程。我的目标是让程序向用户询问一组是/否问题。到目前为止,我一直在使用提示功能进行询问,但我想要一些不那么具有侵略性的东西,比如按钮。问题是我不能让程序等待答案被选中而不使用while循环,冻结程序。 有没有办法让while循环表现?如果不是我该怎么办?
代码(简化,只是功能和按钮):
var currentAnswer = "unanswered"
function Change2Yes(){
currentAnswer = "y"
}
function Change2No(){
currentAnswer = "n"
}
function Change2Maybe(){
currentAnswer = "m"
}
function question(x){
document.write(x)
while (currentAnswer != "y" && currentAnswer != "n" && currentAnswer != "m"){
//do nothing THIS IS THE PART THAT FREEZES THE PROGRAM
}
if(currentAnswer == "y"){
answerlist.push("y");
latestAnswer="y";
}
else if(currentAnswer == "n"){
answerlist.push("n");
latestAnswer="n";
}
else if(currentAnswer== "m"){
answerlist.push("m");
latestAnswer="n";
}
currentAnswer= "unanswered"
}
<button id="btnYes" onclick="Change2Yes()">
Yes
</button>
<button id="btnNo" onclick="Change2No()">
No
</button>
<button id="btnMaybe" onclick="Change2Maybe()">
Maybe
</button>
非常感谢:)
答案 0 :(得分:1)
你应该使用事件。添加点击监听器,例如:
var buttons = Array.prototype.slice.call(document.querySelectorAll('button'));
buttons.forEach(function (button) {
button.addEventListener('click', answer.bind(this, button.value));
});
function answer(currentAnswer) { ... };
单击按钮后将调用answer
函数。