我为朋友创造了一个非常简单的圣诞老人游戏。所以逻辑再次非常简单。给定一个名称列表,用户需要插入他/她的名字,每当点击该按钮时,随机名称将从列表中选取并显示为结果。
我有两个小问题:
我可以在列表中找到并显示随机名称,但如果与用户姓名不同,我无法传递luckyName函数并显示它。
如果当前用户的名称与拾取的名称相同,我不确定如何或者选择其他名称的最佳方式。到目前为止,我只是再次调用pickRandomName函数。
HTML:
<h3>Santa ask: Who are you kid?</h3>
<section>
<input type="text" placeholder="YOUR name bitte, not time for joke.." id='santaName'/>
<div id="go">Go</div>
</section>
JS:
var nameList = [
'gio',
'anna',
'chiara',
'ella',
'sarah',
'sara'
];
$(document).ready(function(){
pickRandomName();
luckyName();
});
var luckyName = function(randomName){
var section = $('section');
$('section').on('click', '#go', function(){
var currentSanta = $('#santaName').val();
console.log(currentSanta);
if( currentSanta != randomName){
console.log(randomName);
$('section').append(randomName);
} else {
//pick up another random name
pickRandomName(randomName);
console.log(randomName);
}
});
};
var pickRandomName = function(randomName){
var randomName = nameList[Math.floor(Math.random() * nameList.length)];
console.log(randomName);
};
答案 0 :(得分:0)
试试这个,
var nameList = [
'gio',
'anna',
'chiara',
'ella',
'sarah',
'sara'
];
$(document).ready(function() {
var randomName = nameList[Math.floor(Math.random() * nameList.length)];
//console.log( nameList[Math.floor(Math.random() * nameList.length)]);
$('#go').on('click', function() {
luckyName(randomName);
});
});
var luckyName = function(randomName) {
var section = $('section');
$('section').on('click', '#go', function() {
var currentSanta = $('#santaName').val();
console.log(currentSanta);
if (currentSanta != randomName) {
console.log(randomName);
$('section').append(randomName);
} else {
//pick up another random name
pickRandomName(randomName);
console.log(randomName);
}
});
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<h3>Santa ask: Who are you kid?</h3>
<section>
<input type="text" placeholder="YOUR name" id='santaName' />
<div id="go">Go</div>
</section>
答案 1 :(得分:0)
以下是代码的工作fiddle。
$(document).ready(function(){
window.randomName =pickRandomName(nameList);/*we have created an global variable which will store randomName*/
luckyName(nameList);
});
function luckyName(nameList){
var section = $('section');
$('section').on('click', '#go', function(){
var currentSanta = $('#santaName').val();
console.log(currentSanta);
if( currentSanta != window.randomName){
console.log(window.randomName);
$('section').append(window.randomName);
}
else {
//pick up another random name
window.randomName = pickRandomName(nameList);/*It will change the global var window.randomName value*/
console.log(x);
}
});
}
function pickRandomName(randomName){
var randomName1 = nameList[Math.floor(Math.random() * nameList.length)];
console.log(randomName1);
return randomName1;
};
我使用 window.randomName
传递函数之间的值(了解有关不同类型的变量here的更多信息)。
通过定义window.randomName
我们已经将一个属性附加到窗口,例如&#34; window.location&#34;,它可以被所有函数随时随地访问,而无需将参数一次又一次地传递给函数,并且函数也可以改变它的值,因此每当我们需要将变量传递给不同的函数时,这是一种方法。