我有2个函数,我想知道如何获取在函数generate()内向函数verify()生成随机数的变量“ foto”,因为indexOf会验证在generate()函数,并将检查此值是否在verify()内部定义的数组之一中。
function generate() {
var score = document.getElementById('score');
var foto = Math.floor(Math.random() *20) + 1;
var fotoDOM = document.querySelector('.foto');
fotoDOM.src = 'foto-' + foto + '.jpg';
console.log(foto);
document.getElementById('photo').style.animation ="appearPerson 1s";
score.innerHTML = foto;
}
document.querySelector('.btn').addEventListener('click', verify);
function verify() {
var yesMeetup = [0,1,2,3,4,5,6,7,8,9,10,12,13,14,15];
var notMeetup = [16,17,18,19,20];
var notButton = document.getElementById('no');
var yesButton = document.getElementById('yes');
var decisao = document.getElementById('decisao');
debugger
if (yesButton) {
if (yesMeetup.indexOf(foto) ) {
decisao.textContent = "You got it";
} else if (notMeetup.indexOf(foto) ) {
decisao.textContent = "wrong";
}
}
else if (notButton) {
if (notMeetup.indexOf(foto) ) {
decisao.textContent = "You Gou it";
} else if (yesMeetup.indexOf(foto) ) {
decisao.textContent = "Wrong";
}
}
}
答案 0 :(得分:0)
在generate
函数外部声明foto变量(这将使其变为全局变量),并且可以在verify
函数中使用它。
建议您阅读有关closures
var foto;
function generate(){
var score = document.getElementById('score');
foto = Math.floor(Math.random() *20) + 1;
var fotoDOM = document.querySelector('.foto');
fotoDOM.src = 'foto-' + foto + '.jpg';
console.log(foto);
document.getElementById('photo').style.animation ="appearPerson 1s";
score.innerHTML = foto;
}
document.querySelector('.btn').addEventListener('click', verify);
function verify()
{
var yesMeetup = [0,1,2,3,4,5,6,7,8,9,10,12,13,14,15];
var notMeetup = [16,17,18,19,20];
var notButton = document.getElementById('no');
var yesButton = document.getElementById('yes');
var decisao = document.getElementById('decisao');
debugger
if(yesButton){
if(yesMeetup.indexOf(foto) ){
decisao.textContent = "You got it";
}else if(notMeetup.indexOf(foto) ){
decisao.textContent = "wrong";
}
}
else if (notButton){
if(notMeetup.indexOf(foto) ){
decisao.textContent = "You Gou it";
}else if(yesMeetup.indexOf(foto) ){
decisao.textContent = "Wrong";
}
}
}
答案 1 :(得分:0)
如果函数foto
需要verify
的值,则该值应该是该函数的参数:
document.querySelector('.btn').addEventListener('click', function() {
var foto = generate();
verify(foto);
});
...
/**
* Generate a thing.
*/
function generate() {
...
return foto;
}
/**
* Veryify the thing.
* @param {Number}
*/
function verify(foto) {
...
}
我鼓励您尽可能地隔离您的函数,以使它们实际上不依赖于外部变量。也许在其中一个内部需要操作DOM,但是如果您可以将这些东西彼此抽象化–在1个函数或一部分代码中进行DOM操作,以及在另一组函数中进行所有其他业务逻辑,则您的代码应更易于阅读/编写/调试。