前端的注意事项

本文通过两个实例详细介绍了HTML中button元素type属性为button与submit的区别。type=button仅触发点击事件,而type=submit则在执行点击事件后还会提交表单。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

  1. 当type=button 和type=submit的区别
    案例1:type=button
    <script type="text/javascript">
        function submit1(){
            alert(document.getElementById('result').value);
            document.getElementById('result').value = "success";
            alert(document.getElementById('result').value);
        }
    </script>
    <form id='form'>
        result: <input type='text' id='result'/>
        <button type="button" onclick="submit1(); " >提交</button>
    </form>
结果:只执行onclick事件

案例2:type=submit

    <script type="text/javascript">
        function submit1(){
            document.getElementById('result').value = "success";
        }
    </script>
    <form id='form'>
        result: <input type='text' id='result'/>
        <button type="submit" onclick="submit1(); " >提交</button>
    </form>
结果:先执行onclick事件,再提交表单

原因:关于button标签的type属性,IE 的默认类型是 “button”,而其他浏览器中(包括 W3C 规范)的默认值是 “submit”,所以应该始终为button标签规定 type 属性。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值