function myFunction() {
var x = Math.floor((Math.random() * 10) + 1);
document.getElementById("demoX").innerHTML = x;
var y = Math.floor((Math.random() * 10) + 1);
document.getElementById("demoY").innerHTML = y;
document.getElementById("demoP").innerHTML = " + ";
document.getElementById("equal").innerHTML = " = ";
document.getElementById("input").innerHTML = "<input id=>";
document.getElementById("check").innerHTML = "<button>Check</button>";
}
function myBunction() {
myFunction();
var b, text;
// Get the value of the input field with id="numb"
b = document.getElementById("input").value;
var D = document.getElementById("demoX").value;
var E = document.getElementById("demoY").value;
// If x is Not a Number or less than one or greater than 10
if (b == E + D) {
text = "Input is ok";
} else {
text = "Input not valid";
}
document.getElementById("demo").innerHTML = text;
}
<p>Click the button to display a random number between 1 and 10.</p>
<button onclick="myFunction()">Try it</button>
<br> <br>
<span id="demoX"></span>
<span id="demoP"></span>
<span id="demoY"></span>
<span id=equal></span>
<span id=input></span>
<span onclick="myBunction()" id=check></span>
<p id="demo"></p>
第一个函数抛出两个随机数,第二个函数应该检查输入表单 person 是否正确,但“document.getElementById("demoX").value”什么也不返回...我正在尝试使用 console.log 检查值但它返回就像没有定义一样。
我只是想合并 w3schools 的两个函数,但这花了我很多时间。 :/
最佳答案
你的问题有四个方面。一:
document.getElementById("demoX").value
不返回任何内容。一个<span>
元素没有value
。它有一个 innerHTML
,就是您用来设置的内容。
两个:
if (b == E + D) {
E
和D
将是字符串。两个字符串相加的结果是一个组合字符串。
"4" + "3"
不是"7"
,就是"43"
.
您想先将它们转换为数字。除此之外,一元 +
可以做到这一点。尝试:
b = +b;
D = +D;
E = +E;
if (b == E + D) {
<小时/>
三:您希望在读出所有值之后重置表单,而不是之前。
<小时/>四:通过innerHTML 动态创建所有这些固定输入字段和按钮有什么用?只需将它们直接放入 HTML 中并让它们放在那里即可。
<小时/>所以...
function reset() {
var x = Math.floor((Math.random() * 10) + 1);
document.getElementById("demoX").innerHTML = x;
var y = Math.floor((Math.random() * 10) + 1);
document.getElementById("demoY").innerHTML = y;
document.getElementById("input").value = "";
document.getElementById("demoP").innerHTML = " + ";
document.getElementById("equal").innerHTML = " = ";
}
function check() {
var b, D, E, text;
// Get the value of the input field with id="numb"
b = +document.getElementById("input").value;
D = +document.getElementById("demoX").innerHTML;
E = +document.getElementById("demoY").innerHTML;
if (b == E + D) {
text = "Input is ok";
} else {
text = "Input not valid";
}
document.getElementById("demo").innerHTML = text;
reset();
}
reset();
<p>Click the button to display a random number between 1 and 10.</p>
<span id="demoX"></span>
<span id="demoP"></span>
<span id="demoY"></span>
<span id="equal"></span>
<input id="input">
<button onclick="check()">Check</button>
<p id="demo"></p>
关于javascript - 函数不合作 :/,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31972315/