javascript - 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 个函数之间共享公共变量。
解决方案
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)
推荐阅读
- laravel - 将主页重定向到经过身份验证的页面 Laravel 8 Jetstream Livewire [已解决]
- reactjs - 仅在登录用户满足特定条件时才显示按钮
- python - 模拟测试类中所有测试用例的导入方法
- javascript - 如何创建类以覆盖 JSON 蓝图 JS
- python - Python CSV 作为字典读入,第 n 行作为标题
- javascript - 如何检查每个表单值,并检查特定的复选框
- javascript - Go 调用 JavaScript 函数失败,因为在 JavaScript 代码中引入了缓冲区
- ruby-on-rails - 未初始化的常量 ActiveStorage::Analyzer::ImageAnalyzer::MiniMagick
- r - R highcharter在客户端下载而不需要exports-server失败
- python - 基于 2 个字段的 Django 过滤器