【问题标题】:How to repeat a process by calling a function in javascript如何通过调用javascript中的函数来重复一个过程
【发布时间】:2019-04-27 14:27:19
【问题描述】:

我最近在上一篇文章中提出了这个简单的功能,方法是使用 prompt() 来获取用户输入。从那时起,我提升自己以使用 HTML 表单输入来达到类似的结果。我无法让方程式刷新。我不确定我做错了什么。简直……

-随机生成 1-10 之间的两个数字...只工作一次

-用户输入答案并比较...有效

-统计总答案和正确答案...有效

-提供一个数字等级...作品

数学生成“getMath()”不会在“result()”结束时重新运行,我不知道为什么。

请随意在语法上打败我。

接下来,我将添加数字并更改操作以逐步提高难度级别。但一步一步。

提前感谢您的时间和洞察力。

var correct = 0,
  wrong = 0,
  ans,
  firstnum = Math.floor(Math.random() * 10 + 1),
  secondnum = Math.floor(Math.random() * 10 + 1),
  total = firstnum + secondnum,
  score,
  input,
  calc = "+";

function getMath() {

  document.getElementById("firstnum").value = firstnum;
  document.getElementById("secondnum").value = secondnum;
  document.getElementById("calc").value = calc;
}

function getAnswer() {

  var input = document.getElementById("userInput").value;
  if (input == total) {
    correct++;
  } else {
    wrong++;
  }
  result();
}


function result() {

  score = correct + wrong;
  percent = correct / score;
  document.getElementById("score").innerHTML = score;
  document.getElementById("ans").innerHTML = correct;
  document.getElementById("percent").innerHTML = percent * 100;
  getMath();
}
<body onload="getMath()">

  <h1>Math Test</h1>

  <input type="text" id="firstnum"></input>
  <input type="text" id="calc">
  <input type="text" id="secondnum">
  <hr>

  <form id="form1" onsubmit="return false">
    <input type="text" id="userInput" placeholder="" size="10">
    <button onclick="getAnswer()">Submit Answer</button>
  </form>

  <p>Total Answered</p>
  <p id="score"></p>
  <p>Answered Correctly</p>
  <p id="ans"></p>
  <p>Your number grade</p>
  <p id="percent">%</p>

</body>

</html>

【问题讨论】:

  • result()的末尾放置一个函数无效吗?
  • The math generation "getMath()" does not re-run at the end of the "result()" and I am not sure why. 看起来它在加载时运行一次,并在提交答案后再次运行。
  • firstnumsecondnumcalc 中的任何值发生更改时,是否要重新运行getmath()
  • 计算用户输入和真假后,我想生成一组新的数字来计算另一个用户输入。

标签: javascript html function validation


【解决方案1】:

您对getMath 的第二次调用运行,但它在页面上没有任何区别。该函数不会选择新的随机值,而只是重新显示已经存在的内容……这些随机值仅在脚本加载时生成一次。

所以将随机化逻辑移入getMath。还要尽量避免过多的全局变量。如果您在每次生成新的数学挑战时为您的按钮分配一个新的单击处理程序,那么您实际上可以传递所有必要的变量并将所有其余变量声明为局部变量。去掉HTML部分的onclick,用代码设置onclick

当用户不应该更改其内容时,还将input 元素更改为span 元素。

这是它的工作原理:

window.onload = () => getMath(0, 0);

function getMath(correct, wrong) {
    var firstnum = Math.floor(Math.random()*10+1),
        secondnum = Math.floor(Math.random()*10+1),
        calc = "+",
        total = firstnum+secondnum;
    document.getElementById("firstnum").textContent = firstnum;
    document.getElementById("secondnum").textContent = secondnum;
    document.getElementById("calc").textContent = calc;
    document.getElementById("userInput").value = "";
    document.getElementById("btnAnswer").onclick = () => getAnswer(total, correct || 0, wrong || 0);
}

function getAnswer(total, correct, wrong){
    var input = document.getElementById("userInput").value;
    if (input == total){
        correct++;
    } else{
        wrong++;
    }
    result(correct, wrong);
}


function result(correct, wrong){
    var score = correct+wrong;
    var percent = correct/score;
    document.getElementById("score").innerHTML = score;
    document.getElementById("ans").innerHTML = correct;
    document.getElementById("percent").innerHTML = percent*100;
    getMath(correct, wrong);
}
<h1>Math Test</h1>

<span id="firstnum"> </span>
<span id="calc"> </span>
<span id="secondnum"> </span>
<hr>

<form id="form1" onsubmit="return false">
    <input type="text" id="userInput" placeholder="" size="10">
    <button id="btnAnswer">Submit Answer</button>
</form>

<p>Total Answered: <span id="score"></span></p>
<p>Answered Correctly: <span id="ans"></span></p>
<p>Your number grade: <span id="percent">%</span></p>

【讨论】:

  • 我看到它有效,但是,我试图理解按钮功能的语法。我似乎无法连接点。我看到了“for”循环,但不理解目标。
  • 按钮函数写成arrow function()是函数的空参数列表。您也可以将其编写为内联 function。你更喜欢什么。没有for 循环。
  • 感谢您的澄清。你的补充很有效。
【解决方案2】:

您没有得到第二轮数字的原因是生成随机数的代码不在getMath() 函数内。随机数代码仅在页面首次加载时运行一次。

现在除此之外,您还有很多冗余/不需要的代码(即,只要我们知道问了多少问题以及您答对了多少,就无需跟踪有多少错误答案)以及您的许多变量的名称不能准确地表达它们所包含的内容。

清理所有内容,减少代码量和复杂性。

查看内联 cmets 了解所做的更改:

// Do all your event binding in JavaScript, not with inline HTML event attributes:
window.addEventListener("DOMContentLoaded", populate);
document.querySelector("button").addEventListener("click", result);

// Declare and initialize all your variables.
var correct = 0;
var numQuestions = null;
var total = null;
var calc = "+";

// Get your DOM references just once and set your variable
// to the element itself, not a property of the element so 
// that if you ever want to get a different property, you
// already have the DOM reference.
var firstNumElement = document.getElementById("firstnum");
var secondNumElement = document.getElementById("secondnum");
var calcElement = document.getElementById("calc");
var input = document.getElementById("userInput")
var numCorrectElement = document.getElementById("score");
var numQuestionsElement =  document.getElementById("ans");
var percentElement = document.getElementById("percent");

function populate() {
  // You need to generate new randoms after each successful guess
  // so these lines need to be in a function that will be called again 
  firstNumElement.textContent = Math.floor(Math.random() * 10 + 1);
  secondNumElement.textContent = Math.floor(Math.random() * 10 + 1);
  calcElement.textContent = calc;
  // prepending a "+" in front of the textContent converts it to a number
  total = +firstNumElement.textContent + +secondNumElement.textContent;
  numQuestions++;  // Update how many questions have been asked
  input.value = ""; // reset the user input
}

function result(){
  // The getAnswer function should just be part of this function.
  // We have a simple if/then here, so the JavaScript ternary syntax is easier:
  correct = input.value == total ? correct + 1 : correct;

  // Only use .innerHTML when the string has HTML in it that needs to be parsed.
  // If not, use .textContent - it's faster and safer.
  numCorrectElement.textContent = correct;
  numQuestionsElement.textContent = numQuestions;
  percentElement.textContent = (correct / numQuestions * 100).toFixed(2) + "%";
  populate();  // Generate new randoms and update the page
}
<h1>Math Test</h1>

<!-- 
  input elements don't have a closing tag
  also, use type=number for numeric input
  But here, since users won't be interacting 
  with this data, don't even use form fields.
-->
<span id="firstnum"></span>
<span type="text" id="calc"></span>
<span type="number" id="secondnum"></span>
<hr>

<!-- You're not submitting data anywhere, so you don't need a form element -->
<input type="number" id="userInput" size="10">
<button type="button">Submit Answer</button>

<p>Total Questions: <span id="ans"></span></p>
<p>Answered Correctly: <span id="score"></span></p>
<p>Your number grade: <span id="percent"></span></p>

【讨论】:

  • 大量有用的提示。谢谢。
猜你喜欢
  • 2015-06-01
  • 2013-06-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-09-12
  • 2014-02-01
  • 1970-01-01
相关资源
最近更新 更多