如何通过用户(输入字段)改变函数内全局变量的值

How to change value by user (inputing field) of global variable inside of function

本文关键字:函数 全局变量 改变 用户 何通过 输入 字段      更新时间:2023-09-26

是否有可能通过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>


我应该使用prompt还是input字段,以及如何影响函数值内部的变化。
如何改变这个变量的值,从3例如到5,而不失去函数效果?

var x = Math.floor((Math.random() * 3) + 1);

您可以使用一个输入,并在函数中读取它的值。我还改进了你的功能一点(而不是改变功能)。

<!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>

看到jsfiddle。

试试:

<!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>

希望对你有所帮助