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>