今天帮同事分析一个页面问题:jquery通过append动态添加标签的时候,导致整个页面全部被刷新,最后的结果就是页面上没有看到新增的标签(通过debug模式,发现是新增成功了,只是页面刷新之后就没有了)。。代码如下:
...
<form >
...
<table id="one">
</table>
<button id="btn">新增</button>
...
</form>
...
<script type="text/javascript">
$(function () {
$("#btn").click(function () {
$("#one").append("<tr> " +
"<td><input type='text' class='form-control'/></td>" +
"<td><input type='text' class='form-control'/></td>" +
"<td><input type='text' class='form-control'/></td>" +
"<td><input type='text' class='form-control'/></td>" +
"<td><input type='text' class='form-control'/></td>" +
"</tr>");
});
});
</script>
分析过程:
1、一开始以为是append导致的页面刷新,所以为了排除这个可能性,单独写一个简单的demo,单独使用append添加标签。发现页面并没有刷新。所以排除是append导致页面刷新了。
2、那么能导致页面刷新的就是表单被提交了。发现使用的是<button>标签,外层有一个form标签。 点击button标签按钮导致form被提交了,这才是页面刷新的关键,所以将button修改为<span>标签就好了(这样就避免了form表单被提交了),修改后的代码如下:
...
<form >
...
<table id="one">
</table>
<span id="btn">新增</span>
...
</form>
...
<script type="text/javascript">
$(function () {
$("#btn").click(function () {
$("#one").append("<tr> " +
"<td><input type='text' class='form-control'/></td>" +
"<td><input type='text' class='form-control'/></td>" +
"<td><input type='text' class='form-control'/></td>" +
"<td><input type='text' class='form-control'/></td>" +
"<td><input type='text' class='form-control'/></td>" +
"</tr>");
});
});
</script>
以上代码是项目中的简写,有些样式等都被我省略了。 至于span和button样式问题,大家可以自行写css、或者使用类似bootstrap的css样式。
总结:
就是button导致的form被提交,导致页面刷新。将button换成不会导致form被提交的标签就行了,比如我换的是span。