1 回答
TA贡献1807条经验 获得超9个赞
您需要添加以防止此行为,并在添加之前将值转换为数字形式:event.preventDefault()
function add(e) {
e.preventDefault();
var num1 = document.getElementById("num1").value;
var num2 = document.getElementById("num2").value;
if(num1 && num2){
var result = Number(num1) + Number(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(event)">Add</button>
</form>
<p id="display"></p>
<script language="javascript" type="text/javascript" src="js.js"></script>
</div>
</body>
</html>
添加回答
举报