javascript - 在 JavaScript 中定义变量并创建按钮?

标签 javascript html

这是我的代码:

<input id="numb" type="number" align="center">

<button type="button" onclick="myFunction()" align="center">Submit</button>

<p id="demo"></p>

<script>
function myFunction() {
    var x, text;

    // Get the value of the input field with id="numb"
    x = document.getElementById("numb").value;

    if (x == 1) {
        text = "Fantasy World";
    } 
    if (x == 2) {
    text = "Sir Wags A Lot";
    }
    if (x == 3) {
    text = "Take a Path";
    }
    if (x == 4) {
    text = "River Clean Up"
    }
    if (x == 5) {
    text = "Pinball"
    }
    if (x == 6) {
    text = "Ghost Girl"
    }
    if (x == 7) {
    text = "Dress Up"
    }
    if (x == 8) {
    text = "Where Is My Hat?"
    }
    if (isNaN(x) || x < 1 || x > 8) {
         text = "Input not valid";
    }

    document.getElementById("demo").innerHTML = text;
}
</script>

我需要编写代码,为用户提供一个按钮,在输入框中输入有效数字后确认其订单。
例如:

if (x == 1) {
    text = "Example"
}

然后从那里创建另一个按钮,他们可以单击该按钮来确认这一点。然后他们应该看到一些文字,上面写着“已确认的订单”——有人可以帮助我吗? :)

最佳答案

您可以使用下面的代码-

<input id="numb" type="number" align="center">

<button type="button" onclick="myFunction()" id="primary" align="center">Submit</button>

<p id="demo"></p>

<script>
function myFunction() {
    var x, text="Fantasy World";

    // Get the value of the input field with id="numb"
    x = document.getElementById("numb").value;

    if (x == 1 && document.getElementById("confirm")==null) {
        text = "Fantasy World";
        var demo=document.getElementById("demo");
        var span=document.createElement("span");

        span.innerHTML="<button onclick='confirmMessage()' id='confirm'>Confirm</button>";
        document.body.appendChild(span);
    } 
    if (x == 2) {
    text = "Sir Wags A Lot";
    }
    if (x == 3) {
    text = "Take a Path";
    }
    if (x == 4) {
    text = "River Clean Up"
    }
    if (x == 5) {
    text = "Pinball"
    }
    if (x == 6) {
    text = "Ghost Girl"
    }
    if (x == 7) {
    text = "Dress Up"
    }
    if (x == 8) {
    text = "Where Is My Hat?"
    }
    if (isNaN(x) || x < 1 || x > 8) {
         text = "Input not valid";
    }

    document.getElementById("demo").innerHTML = text;
}
function confirmMessage()
{
  alert("Confirmed order");
}
</script>

关于javascript - 在 JavaScript 中定义变量并创建按钮?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29746917/

相关文章:

javascript - 复选框设置状态,并在 React 中重置

javascript - 如何在 Redux/React 中处理 UI 状态 - Redux-UI?

html - 如何在没有滚动条的情况下一次在 html 页面中嵌入 pdf 文件?

python - 在 python 中打印列表中的所有项目时出现问题

javascript - 很棒的设置标签文本字段和隐藏字段值

javascript - 如何在jquery中选择ul的li元素?

javascript - 画一条连接数据点的线

javascript - D3.js 将整数轴更改为字符串

jquery - 更改 fancybox 设计 - 添加另一个不晃动窗口的 div

javascript - 如何将 display flex div 滚动到底部