表单提交与按钮点击事件冲突

表单提交与按钮点击事件冲突

问题原因:想在前端写一个计算器,使用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>

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值