为什么我提交表单后结果不保留?

我正在尝试添加两个放在输入字段中的数字。然后我想显示结果,但结果立即消失。


function add() {

    var num1 = document.getElementById("num1").value;

    var num2 = document.getElementById("num2").value;

    

    var result = num1 + num2;

    var display = document.getElementById("display");

    display.append(result);

}

<!DOCTYPE html>

<html>

    <head>

        <meta charset="utf-8">

        <title>JS</title>

    </head>

    <body id="body">

            <form action="" id="form">

                <label for="num1">Number 1</label>                

                    <input type="number" name="num1" id="num1">

                <label for="num2">Number 2</label>

                    <input type="number" name="num2" id="num2">

                <button id="submit" onclick="add()">Add</button>

            </form>

            <p id="display"></p>

            <script language="javascript" type="text/javascript" src="js.js"></script>

        </div>

    </body>

</html>

我做错了什么?感谢您的任何帮助!


慕容森
浏览 121回答 1
1回答

函数式编程

您需要添加以防止此行为,并在添加之前将值转换为数字形式:event.preventDefault()function add(e) {&nbsp; &nbsp; e.preventDefault();&nbsp; &nbsp; var num1 = document.getElementById("num1").value;&nbsp; &nbsp; var num2 = document.getElementById("num2").value;&nbsp; &nbsp; if(num1 && num2){&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;var result = Number(num1) + Number(num2);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;var display = document.getElementById("display");&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;display.append(result);&nbsp; &nbsp; }}<!DOCTYPE html><html>&nbsp; &nbsp; <head>&nbsp; &nbsp; &nbsp; &nbsp; <meta charset="utf-8">&nbsp; &nbsp; &nbsp; &nbsp; <title>JS</title>&nbsp; &nbsp; </head>&nbsp; &nbsp; <body id="body">&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <form action="" id="form">&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <label for="num1">Number 1</label>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <input type="number" name="num1" id="num1">&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <label for="num2">Number 2</label>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <input type="number" name="num2" id="num2">&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <button id="submit" onclick="add(event)">Add</button>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; </form>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <p id="display"></p>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <script language="javascript" type="text/javascript" src="js.js"></script>&nbsp; &nbsp; &nbsp; &nbsp; </div>&nbsp; &nbsp; </body></html>
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript