html神坑之button的type属性

174 阅读1分钟

1、入坑记录

不知道第几次入坑这个button的type属性了,今天我要记录一下,告诫一下自己。经常你回发现正确的jquery语句,但是点击事件却没有反应,如果你不调试,你可能发现不了问题,其实效果已经出来了,但是页面刷新了,导致跟没效果一样。

2、代码演示(错误)

<html>
<head>
<title>Insert title here</title>
<script src="https://cdn.bootcss.com/jquery/3.2.0/jquery.min.js"></script>
<script type="text/javascript">
	$(function(){
		$("#add").click(function(){
                    $("#add").attr('disabled',true);
                    $("#add").text('已发送');
                    $("#br").before("验证码: <input type='text' name='checkcode'/>");
		});
	});
</script> 
</head>
<body>
	<form action="#" method="post">
		手机号: <input type="text" name="phone"><button id="add"> 发送验证码</button>
		<br>
		<br id="br">
	</form>
</body>
</html>

3、代码演示(正确)

<html>
<head>
<title>Insert title here</title>
<script src="https://cdn.bootcss.com/jquery/3.2.0/jquery.min.js"></script>
<script type="text/javascript">
	
	$(function(){
		$("#add").click(function(){
                    $("#add").attr('disabled',true);
                    $("#add").text('已发送');
                    $("#br").before("验证码: <input type='text' name='checkcode'/>");
		});
	});
</script> 
</head>
<body>
	<form action="#" method="post">
		手机号: <input type="text" name="phone"><button type="button" id="add"> 发送验证码</button>
		<br>
		<br id="br">
	</form>
</body>
</html>

总结:

button标签的type属性在IE浏览器默认是button,但在其他浏览器默认是submit,所以写button的时候最好都指定其type属性,不要省事,不然入坑很难找到原因的。