【问题标题】:Inverting the rows in dynamic html table using jquery使用jquery反转动态html表中的行
【发布时间】:2018-03-21 02:43:01
【问题描述】:

我有我的 html 表,它使用 jquery 将行附加到最后一行 例如

我想要什么

row1>> 刚刚发布

row2>> 1 分钟前发布

row3>> 2 分钟前发布

但它显示像

row1>> 2 分钟前发布

row2>> 1 分钟前发布

row3>>刚刚发布


<tbody>
  <table align="center" style="width:auto" id="ex-table">
    <tr id="tr">
      <center><th>Date of join</th></center>
      <center><th>name</th></center>
      <center><th>designation</th></center>
      <center><th>exprience</th></center>
      <center><th>salary</th></center>
    </tr> 
  </table> 
</tbody>


<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
    var database = firebase.database().ref().child('user');
    database.on('value', function(snapshot){
        if(snapshot.exists()){
            var content = ' ';
            snapshot.forEach(function(data){
                var val = data.val();
               content +='<tr>';
                content += '<td>' + val.daeofjoin + '</td>';
                content += '<td>' + val.name + '</td>';
                content += '<td>' + val.designation + '</td>';
                content += '<td>'  + val.experience + '</td>';
                content += '<td>'  + val.salary + '</td>';
           content += '</tr>';
            });
            $('#ex-table').append(content)
        }
    });
</script>           

【问题讨论】:

    标签: jquery html dynamic-tables


    【解决方案1】:

    您可以在forEach 循环中使用append()/prepend(),具体取决于您将获得的结果

    snapshot.forEach(function(data){
        var val = data.val();
            content ='<tr>';  // <<<< remove + from here 
            content += '<td>' + val.daeofjoin + '</td>';
            content += '<td>' + val.name + '</td>';
            content += '<td>' + val.designation + '</td>';
            content += '<td>'  + val.experience + '</td>';
            content += '<td>'  + val.salary + '</td>';
            content += '</tr>';
            $('#ex-table').append(content); //$('#ex-table').prepend(content);
     });
    

    注意:不要忘记从第一个 content = 中删除 + 号 .. if append() 无法按预期工作,您可以尝试使用 prepend() $('#ex-table').prepend(content);

    实际上我不知道我的代码是否可以与firebase 一起使用.. 但是如果它可以正常工作,您可以尝试一下,如果不行,您仍然可以查看firebase -> date order reverse

    编辑..我刚刚意识到(来自评论)我的代码会将标题行推到底部..所以你可以使用insertAfter()$(content).insertAfter('#ex-table &gt; tr:first');这行代码将插入新的第一行之后的行

    【讨论】:

    • 非常感谢....我使用 prepend 但(表标题)也将返回到最后一行
    • @Shiva 抱歉,请稍等
    • @Shiva 尝试$(content).insertAfter('#ex-table &gt; tr:first'); 而不是追加或前置行
    • sorryeven that doesn't work it make the entire table to freeze
    • @Shiva 不是它不应该.. 但是当你给第一行id="tr" 你可以试试$(content).insertAfter('#tr');
    猜你喜欢
    相关资源
    最近更新 更多
    热门标签