我正在创建一个Quiz,其中出现一个随机生成的对象属性(object.name),用户输入一个文本值以匹配关联的对象属性(object.number)。我的功能正常工作(当值匹配时返回“正确”,“不正确时返回”),但我希望问题重复,直到用户得到正确的答案。现在,即使用户输入的值不正确,随机生成一个新问题。你能帮我构建一个这样的问题,直到用户输入匹配的属性值为止,它会重复相同的问题吗?
<body>
<h3 id="randThing"></h3>
<form name="userInputForm">
<input type="text" id="userIndexInput"></form>
<button type="button" id="enter" onClick="compareAnswer()">Validate</button>
<script type="text/javascript">
function object(name, value)
{
this.name=name;
this.value=value;
}
var car=new object("Car","50333");
var desk=new object("Desk","10420");
var monkey=new object("Monkey","11450");
var a = [car,desk,monkey];
var randomValue = a[Math.floor(a.length * Math.random())];
var specificThing = randomValue;
document.getElementById("randThing").innerHTML=specificThing.name;
var specificThingValue = specificThing.value;
function compareAnswer()
{
var x = document.getElementById("userIndexInput").value;
if (x === specificThingValue)
{
alert("Correct!");
document.getElementById("randThing").innerHTML=randomValue;
}
else
{
alert("Try Again!");
//don't know what to put here to make same the same specificThing generate again until x === specificThingValue
}
};
</script>
答案 0 :(得分:0)
你所做的一切都很好。我认为你对randomValue
和specificValue
感到困惑。
这是实现目标的简单方法。
function QuestionObject(name, value)
{
this.name=name;
this.value=value;
}
var car = new QuestionObject("Car","50333");
var desk = new QuestionObject("Desk","10420");
var monkey = new QuestionObject("Monkey","11450");
var Questions = [car, desk, monkey];
var randomValue;
function generateQuestion()
{
document.getElementById("userIndexInput").value = "";
randomValue = Questions[Math.floor(Questions.length * Math.random())];
document.getElementById("randThing").innerHTML=randomValue.name;
}
generateQuestion();
function compareAnswer()
{
var x = document.getElementById("userIndexInput").value;
if (x === randomValue.value)
{
alert("Correct!");
generateQuestion();
}
else
{
alert("Try Again!");
}
};
只需稍微更改变量名称即可。如果您希望在行动http://jsfiddle.net/RR2h4/3/中看到这一点,那么这是一个小提琴。