我正在使用javascript进行文字游戏。
我需要将onclick事件创建的随机数传递给另一个函数。另一个函数触发onclick事件。
(我已经尝试将随机数作为参数发送给新的 功能和它工作,但不是与clickevent)
第一种方法spelet.word,从10个单词的数组中选择一个随机的英语单词。
第二种方法spelet.answer检查它是否拼写正确。它是通过从第一种方法中获取相同的随机生成的数字来为单词数组选择正确的单词。
问题是我无法使用onclick从第一个方法中随机创建数字。
相关的HTML
<form>
<input type="text" value="eng" id="eng" />
<!-- the english word-->
<input type="text" value="sve" id="sve" />
<!-- the swedish word-->
<input type="button" value="Nytt Ord" onclick='spelet.word();' />
<br />
<!-- Generates a random english word from an array of 10 words-->
<input type="button" value="Svara" onclick='spelet.answer();' />
<br />
<!-- The user use this button to submit the swedish word-->
</form>
&#13;
var $Lars = {};
var objwords = //Måste ha som global för att alla metoder ska nå den.
{
ord: [{
eng: "bird",
sve: "fågel"
}, {
eng: "car",
sve: "bil"
}, {
eng: "food",
sve: "mat"
}, {
eng: "coffee",
sve: "kaffe"
}, {
eng: "water",
sve: "vatten"
}, {
eng: "woman",
sve: "kvinna"
}, {
eng: "cup",
sve: "kopp"
}, {
eng: "pen",
sve: "penna"
}, {
eng: "beer",
sve: "öl"
}, {
eng: "desert",
sve: "öken"
}, {
eng: "stone",
sve: "sten"
}]
}
$Lars.Play = function()
{
var c;
this.word = function() {
//---------- doing a random number-----------------//
var c = Math.floor(Math.random() * 10) + 1;
//spelet.answer(c); DID NOT WORK
document.getElementById('eng').value = objwords.ord[c].eng;
var i = 0; //using the random number to pick up en english word
for (i = 0; i < objwords.ord.length; i++) {
document.getElementById('eng').value = objwords.ord[c].eng;
}
document.getElementById('nr').value = c;
//return c; DID NOT WORK
}
this.answer = function() //the same random number picks up the swedish word and
//check if it is correct spelled
{
var svaret = document.getElementById('sve').value;
var q = 0;
for (q = 0; q < objwords.ord.length; q++) {
if (objwords.ord[c].sve == svaret) {} //something happens when correct answer;}
else {} //something happens when incorrect answer;}
}
}
}
var spelet = new $Lars.Play();
&#13;
答案 0 :(得分:0)
你需要一个更全局范围的变量。一个最小的例子:
function Play (){
this.c = -1;
}
Play.prototype.word = function(){
this.c = Math.floor(Math.random() * 10) + 1;
console.log("Produced: " + this.c);
}
Play.prototype.answer = function(){
console.log("Got " + this.c);
}
var playit = new Play();
playit.word();
playit.answer();
playit.word();
playit.answer();
你不需要拼出原型,我只是觉得它会更明显。