【博学谷学习记录】超强总结,用心分享 |button按钮闪退原因

本文介绍了一个常见的前端问题:当表单内的按钮触发事件后,由于默认提交行为导致页面刷新,使得控制台输出的信息瞬间消失。文章提供了错误代码示例及修正方案。

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

1.需求:点击button按钮,获取三个input文本框的数据并打印在控制台上、

2.错误代码:程序没有任何报错提示,点击按钮的时候,控制台成功打印后被立刻清除


<html lang="en">
    <script>
        window.onload = function(){
            // 先获得元素数据源:input,触发源:button,作用源:tbody
            var inps = document.querySelectorAll('input');
            var btn = document.querySelector('button');
            var tb = document.querySelector('tbody');
            //添加btn数据
            btn.onclick = function(){
                var arr2 = [];
                for(m = 0;m < inps.length;m++){
                    arr2[m] = inps[m].value;
                }
                console.log(arr2); 
            }
        }
    </script>
</head>
<body>
    <form action="">
        商品名:<input type="text">
        价格:<input type="text" >
        数量:<input type="text">
        <button>添加</button>
     </form>
    <table>
        <thead>
            <tr>
                <th>商品名</th>
                <th>价格</th>
                <th>数量</th>
            </tr>
        </thead>
        <tbody>

        </tbody>
    </table>
</body>
</html>

3.错误原因:

给button设置了onclick时间,其实没有太大的问题,而出现闪退的原因是因为表单元素:<form></form>上。按钮执行了点击事件,就相当于表单提交了数据,表单提交数据之后,页面会重新刷新,又因为button也在<form></form>中,所以button的所有数据以及绑定的事件都被还原到初始状态,因此在onclick执行的一瞬间,就又被拉回去了,也就是我们看到的闪退。

想要解决这个问题其实特别简单,将<form></form>标签删除掉,或者将button写到<form></form>的外面就可以了。

4.正确代码:

<html lang="en">
    <script>
        window.onload = function(){
            // 先获得元素数据源:input,触发源:button,作用源:tbody
            var inps = document.querySelectorAll('input');
            var btn = document.querySelector('button');
            var tb = document.querySelector('tbody');

            //添加btn数据
            btn.onclick = function(){
                var arr2 = [];
                for(m = 0;m < inps.length;m++){
                    arr2[m] = inps[m].value;
                }
                console.log(arr2);
                
                
            }
            
        }
    </script>
</head>
<body>
    <!-- <form action="">  把form注释掉就可以解决问题啦~ -->
        商品名:<input type="text">
        价格:<input type="text" >
        数量:<input type="text">
        <button>添加</button>
    <!-- </form> -->
    <table>
        <thead>
            <tr>
                <th>商品名</th>
                <th>价格</th>
                <th>数量</th>
            </tr>
        </thead>
        <tbody>

        </tbody>
    </table>
</body>
</html>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值