首页 文章

使用jquery从sql追加行,导致所有行首先附加在thead中

提问于
浏览
0

我打算使用jquery从sql追加行,但是导致所有行首先附加在thead中 .

enter image description here

而代码是

<body>
    <table id="table">
    <thead><td>A</td><td>B</td><td>C</td><td>D</td><td>E</td><td>F</td><td>G</td></thead>
    </table>
</body>
</html>
<script>
$(document).ready(function(){
    var sql = "select*from test";
    $.ajax({
        url:"query.php",
        data:{
            sqls:sql
        },
        async:false,
        success:function(data){
            var returned_data = JSON.parse(data);
            for(var i=0;i<returned_data.length;i++){
                var temp_str = "<tr class='row'>";
                temp_str += "<td class='cell'>";
                temp_str += "<input class='cell_vale' type='text' value='";
                temp_str += returned_data[i]['firstcell']+"'>";
                temp_str += "</td>";
                ... the other 5 cells is same ...
                temp_str += "</tr>";
                $("table").append(temp_str);
            }
        }
    });
});
</script>

我尝试使用tbody但失败了,
也试图删除thead,
但在它之后,桌子宽度不适合细胞,
如果一行中有多个单元格,则单元格可以显示为2行但是一行 .

任何人都可以帮助我吗?谢谢

1 回答

  • 0

    首先,我建议使用现代数据绑定方法,以便更轻松,更清晰地实现您要做的事情 . 看看VueJSReact,他们肯定会帮助你大大的时间!

    其次,尝试将你的 temp_str 和行附件移动到for..loop之外,就像这样

    var returned_data = [
        { firstcell: 'cell1' },
        { firstcell: 'cell2' },
        { firstcell: 'cell3' }
    ];
    
    var temp_str = "";
    
    for(var i = 0; i < returned_data.length; i++) {
        temp_str += "<tr class='row'>";
        temp_str += "<td class='cell'>";
        temp_str += "<input class='cell_vale' type='text' value='";
        temp_str += returned_data[i]['firstcell'] + "'>";
        temp_str += "</td>";
        temp_str += "</tr>";
    }
    
    $("table").append(temp_str);
    

    看看它是否适合你?

相关问题