首页 > 解决方案 > 2个函数如何在JavaScript中共享公共变量

问题描述

    var ques=["Qno 1", "Qno 2","Qno 3","Qno 4","Qno 5","Qno 6","Qno 7","Qno 8","Qno 9","Qno 10"];
var ans  =[1,2,3,4,5,6, 7,8,9,10];
function random()
{
  var qno=Math.floor((Math.random() * 10) );
  return qno;
}

function validate()//here need help
{
  var Rans=document.getElementById("numb").value;
  if (Rans == ans[qno])
     alert("validated!!!");
  else 
     alert("Not a valid entry.. declined!!!");
}
function execution()
{
  var x = document.getElementById("myDIV");
  if (x.style.display === "none") { x.style.display = "block";} 
  else {x.style.display = "none";}
  
  var qno1=random(); 
  document.getElementById("demo").innerHTML = ques[qno1];
  
  var qno2=random(); 
  if(qno1==qno2)
    qno2=random();
   document.getElementById("demos").innerHTML = ques[qno2];
}

在上面的代码中,我试图生成随机问题。这只是我代码的 javascript 部分。从第一个开始,两个数组分别是 questions 和 sol。代码执行成功,但验证部分有问题。对于验证,我想在按下 HTML 按钮标记中的提交按钮时将 qno1 值传递给验证函数。请帮助我执行此代码以及我们如何在 2 个函数之间共享公共变量。

标签: javascripthtmlfunction

解决方案


You need to scope the vars to outside of your functions so you can use them in both.

        var ques=["Qno 1", "Qno 2","Qno 3","Qno 4","Qno 5","Qno 6","Qno 7","Qno 8","Qno 9","Qno 10"];
var ans  =[1,2,3,4,5,6, 7,8,9,10];

//move scope of vars
var qno1

function random()
{
  var qno=Math.floor((Math.random() * 10) );
  return qno;
}

function validate (qno)// use it here by passing it in
{
  var Rans=document.getElementById("numb").value;
  if (Rans == ans[qno])
     alert("validated!!!");
  else 
     alert("Not a valid entry.. declined!!!");
}
function execution()
{
  var x = document.getElementById("myDIV");
  if (x.style.display === "none") { x.style.display = "block";} 
  else {x.style.display = "none";}
  
// set here
  qno1=random(); 
  document.getElementById("demo").innerHTML = ques[qno1];
  
  var qno2=random(); 
  if(qno1==qno2)
    qno2=random();
   document.getElementById("demos").innerHTML = ques[qno2];
}

// call it wherever
validate(qno1)

推荐阅读