[英]Re-run JavasScript <script> code without refreshing the page
[英]Re-run javascript on a page without refreshing/reloading the entire page
我正在使用 JavaScript 生成一些随机数。 然后根据用户输入检查这些随机数,并显示正确/不正确的结果。 然后我有一个按钮可以刷新页面以生成新的随机值。
我想知道是否有更好的方法可以重新运行 JavaScript 而无需再次重新加载整个页面。
//Generates a pair of very peculiar two digit random numbers
function getRandomInt(min, max) {
min = Math.ceil(min);
max = Math.floor(max);
return Math.floor(Math.random() \* (max - min + 1)) + min;
}
let a = getRandomInt(2,9);
let b = getRandomInt(0,8);
let d = getRandomInt(1,a-1);
let e = getRandomInt(b+1,9);
let ab ="" + a + b;
document.getElementById("AB").innerHTML = ab;
let de ="" + d + e;
document.getElementById("DE").innerHTML = de;
// finds their difference
let result = ab-de;
document.getElementById("R").innerHTML = result;
//checks the user input against correct result and displays a correct/incorrect message
function myFunction() {
let x = document.getElementById("numb").value;
let text;
if (x == result) {
text = "Correct";
} else {
text = "incorrect";
}
document.getElementById("demo").innerHTML = text;
}
现在我希望新值在按下按钮时出现。 一种方法是简单地刷新我当前正在做的页面。 我想知道是否有更好的方法来做到这一点。 我尝试将整个脚本封装在 function 中并使用按钮调用它。 它有效,但由于某种原因它破坏了结果检查功能。
PS:除了我在构建这个小项目时获得的经验外,我在 HTML/JS 方面没有任何经验。 非常感谢任何帮助。
您已经接近将所有内容放入另一个 function 的想法,但还不够。 与其重新运行所有内容,另一个 function 只生成新数字并更新 UI 应该可以解决问题。
// Generates a pair of very peculiar two digit random numbers
function getRandomInt(min, max) {
min = Math.ceil(min);
max = Math.floor(max);
return Math.floor(Math.random() * (max - min + 1)) + min;
}
// Generate a new set of numbers
function getNewIntsToCheck() {
const a = getRandomInt(2,9);
const b = getRandomInt(0,8);
const d = getRandomInt(1,a-1);
const e = getRandomInt(b+1,9);
const ab ="" + a + b;
const de ="" + d + e;
const result = ab-de;
return { ab, de, result }
}
// Set in parent scope for access in myFunction
// There are other ways to do this, but this should be easy to understand since
// you don't have much experience with JS :)
let res = ""
// Update the UI on the click of the refresh button
function onRefreshButtonClick() {
const { ab, de, result } = getNewIntsToCheck()
// Set res from parent scope
res = result
document.getElementById("R").innerHTML = result;
document.getElementById("AB").innerHTML = ab;
document.getElementById("DE").innerHTML = de;
}
// Check current numbers in UI against user input and display message
function myFunction() {
let x = document.getElementById("numb").value;
let text;
// Check against res from parent scope, which was set in
// onRefreshButtonClick
if (x == res) {
text = "Correct";
} else {
text = "incorrect";
}
document.getElementById("demo").innerHTML = text;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.