[英]How to change value by user (inputing field) of global variable inside of function
Is it possible by prompt
or somehow that user's can change the value of variable inside this function: 用户是否可以通过
prompt
或某种方式更改此函数内变量的值:
<!DOCTYPE html>
<html>
<body>
<center>
<button onclick="myFunction()" style="font-size: 17pt; margin-top: 5%;">Roll it</button>
</center>
<br>
<center>
<span id="demo" style="margin: 10% 5%; font-size: 45pt; color: blue;"></span>
<span id="demo1" style="margin: 2% 5%; font-size: 45pt; color: red;"></span>
</center>
<script>
function myFunction() {
var x = Math.floor((Math.random() * 3) + 1);
document.getElementById("demo").innerHTML = x;
var y = Math.floor((Math.random() * 3) + 1);
document.getElementById("demo1").innerHTML = y;
if (x == y) {
myFunction();
}
else {
}
}
</script>
</body>
</html>
Should I use prompt
or input
field's, and how to affect the changes inside function value. 我应该使用
prompt
字段还是input
字段,以及如何影响函数值内部的更改。
How to change the value of this variable, from 3
eg to 5
but without loosing the function effect? 如何在不失去函数效果的情况下将该变量的值从
3
例如5
更改为5
?
var x = Math.floor((Math.random() * 3) + 1);
You can use an input, and read it's value in your function. 您可以使用输入,并在函数中读取其值。 I also improved your function a little (while not changing functionality).
我还对您的功能进行了一些改进(虽然未更改功能)。
<!DOCTYPE html>
<html>
<body>
<center>
<input type="number" id="max" value="3"/>
<button onclick="myFunction()" style="font-size: 17pt; margin-top: 5%;">Roll it</button>
</center>
<br>
<center>
<span id="demo" style="margin: 10% 5%; font-size: 45pt; color: blue;"></span>
<span id="demo1" style="margin: 2% 5%; font-size: 45pt; color: red;"></span>
</center>
<script>
function myFunction() {
var max = document.getElementById('max').value || 3;
var x = Math.floor((Math.random() * max) + 1);
document.getElementById("demo").innerHTML = x;
do {
var y = Math.floor((Math.random() * max) + 1);
} while (x === y);
document.getElementById("demo1").innerHTML = y;
}
</script>
</body>
</html>
Try this way: 尝试这种方式:
<!DOCTYPE html>
<html>
<body>
<center>
<input type="text" id="var" />
<br>
<button onclick="myFunction()" style="font-size: 17pt; margin-top: 5%;">Roll it</button>
</center>
<br>
<center>
<span id="demo" style="margin: 10% 5%; font-size: 45pt; color: blue;"></span>
<span id="demo1" style="margin: 2% 5%; font-size: 45pt; color: red;"></span>
</center>
<script>
function myFunction() {
debugger
var x = Math.floor((Math.random() * document.getElementById("var").value) + 1);
document.getElementById("demo").innerHTML = x;
var y = Math.floor((Math.random() * document.getElementById("var").value) + 1);
document.getElementById("demo1").innerHTML = y;
if (x == y) {
myFunction();
}
else {
}
}
</script>
</body>
</html>
Hope help you 希望对你有帮助
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.