表单提交与按钮点击事件冲突
问题原因:想在前端写一个计算器,使用javascript单击事件控制form表单提交的时候,出现了问题.
代码如下:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>单击和双击事件</title>
</head>
<body>
<form action="">
<input type="text">+
<input type="text">
<input type="submit" value="计算">
<span>结果是:<strong style="color:red"></strong></span>
</form>
<script>
//当提交表单的时候,获取两个input标签的值,然后想加,最后赋值给strong标签的文本值。
//获取input标签
let input = document.querySelectorAll("input");
//获取strong标签
let strong = document.querySelector("strong");
//将submit标签绑定单机事件
input[2].onclick = function () {
console.log(input[0]);
console.log(input[1]);
}
</script>
</body>
</html>
页面如下:
问题描述:
当我们点击按钮"计算"时,console打印的结果,一闪而过.
解决办法.
1.使用button代替input标签
代码如下
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>单击和双击事件</title>
</head>
<body>
<form action="">
<input type="text">+
<input type="text">
<!-- <input type="submit" value="计算"> -->
<button type="button">计算</button>
<span>结果是:<strong style="color:red"></strong></span>
</form>
<script>
//当提交表单的时候,获取两个input标签的值,然后想加,最后赋值给strong标签的文本值。
//获取input标签
let input = document.querySelectorAll("input");
//获取strong标签
let strong = document.querySelector("strong");
// 获取button标签
let button = document.getElementsByTagName("button")[0];
// console.log(button);
//将submit标签绑定单机事件
button.onclick = function () {
console.log(input[0]);
console.log(input[1]);
}
</script>
</body>
</html>
2.这种情况是因为form后action属性没有值导致的,我们可以删除action属性或者给action属性增加一个值.
代码如下
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>单击和双击事件</title>
</head>
<body>
<form action="#">
<input type="text">+
<input type="text">
<input type="submit" value="计算">
<span>结果是:<strong style="color:red"></strong></span>
</form>
<script>
//当提交表单的时候,获取两个input标签的值,然后想加,最后赋值给strong标签的文本值。
//获取input标签
let input = document.querySelectorAll("input");
//获取strong标签
let strong = document.querySelector("strong");
//将submit标签绑定单机事件
input[2].onclick = function() {
console.log(input[0]);
console.log(input[1]);
}
</script>
</body>
</html>