javascript - 使用 jquery 避免重复

标签 javascript jquery

如何使用jquery避免重复数据? 我的代码是:

<button  id="gen">Generate</button>
<table id="report" border="1" style="visibility:hidden">
    <tr>
        <th>Sl.No.</th>
        <th>District Name</th>
    </tr>
</table>

js:

$("#gen").click(function(){
$("#report").css("visibility","visible");
for(var i=0; i<5; i++){
  var row='<tr><td>('+(i+1)+')</td></tr>'
  $("#report").append(row);
 }
});

每次我单击按钮时,都会显示相同的数据。 如何避免呢? sqlfiddle: http://jsfiddle.net/etdx5o08/

最佳答案

这样做:

$("#gen").click(function() {
       $("#report").parent().show();
       var rows='';
       for (var i = 0; i < 5; i++) {
         rows = rows+'<tr><td>(' + (i + 1) + ')</td><td></td></tr>'
       }
       $("#report").html(rows);
     });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="gen">Generate</button>
    <table border="1" style="display:none">
        <thead>
            <tr>
                <th>Sl.No.</th>
                <th>District Name</th>
            </tr>
        </thead>
        <tbody id="report"></tbody>
    </table>

关于javascript - 使用 jquery 避免重复,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29815843/

相关文章:

javascript - 使用 JSON 数据在 html 中填充 ul

javascript - 在 Recaptcha.reload() 完成后执行代码

javascript - JQuery ajax停止数据的urlencode

javascript - webpack 卡在 "95% emit"/"95% emitting"

javascript - Capistrano post deploy uglify-js 钩子(Hook)输出但不写入文件

javascript - 从数据库填充数据时,Jquery token 输入不起作用

使用ajax的php-mysql登录系统

javascript - 如何更新 Controller 中定义的变量作为语法?

javascript - PhoneGap打开原生 map

javascript - JavaScript “ended”函数无法正常运行