刷新数据而不删除整个表

时间:2013-11-14 18:38:11

标签: jquery html ajax

我得到了我想要的结果,当我按下按钮时,它会删除我不想要的整个表格。

这是我的jquery

$(document).ready(function() {
$('#button1').click(function(event) {
    $('#list').empty();
    $.ajax({
        url : 'http://98.199.64.63/api/eric_api.php?q=series',
        type : 'GET',
        dataType : 'json',
        success : function(data) {
            var table = $("#list");
            //table.html('');
            $.each(data, function(idx, elem) {
                table.append("<tr><td>" + elem.id + "</td>" + "<td>" + elem.user + 
                "</td>" + "<td>" + elem.email + "</td>" + "<td>" + elem.summary + "</td>" +
                "<td>" + elem.due_date + "</td>" + "<td>" + elem.problem_type + "</td>"+
                "<td>" + elem.status + "</td></tr>");
            });
        },
        error : function() {
            alert('There was an error');
        }
    });
});
});

这是我的HTML

<!DOCTYPE html>


<html>
<head>
    <title></title>
    <script src="js/jquery.js"></script>
    <script src="js/api_calls.js"></script>
    <link rel="stylesheet" href="css/normalizer.css" />
    <link rel="stylesheet" href="style.css" />
</head>

<body>
    <div>
        <table id="list">
            <tr>
                <th>ID</th>
                <th>User</th>
                <th>Email</th>
                <th>Summary</th>
                <th>Due Date</th>
                <th>Problem Type</th>
                <th>Status</th>
            </tr>
        </table>
    </div>
    <div>
        <button id="button1">Get Data</button>
    </div>
</body>
 </html>

我只想在td标签中刷新数据而不是th标签。任何帮助谢谢

2 个答案:

答案 0 :(得分:1)

选项1

您可以随时删除第一个TR之后的任何TR,然后使用新数据附加表格。

var table = $("#list");
table.find('tr:gt(0)').remove();

$.each(data, function(idx, elem) {
    table.append("<tr><td>" + elem.id + "</td>" + "<td>" + elem.user + 
    "</td>" + "<td>" + elem.email + "</td>" + "<td>" + elem.summary + "</td>" +
    "<td>" + elem.due_date + "</td>" + "<td>" + elem.problem_type + "</td>"+
    "<td>" + elem.status + "</td></tr>");
});

选项2

另一个选择是使用<thead><tbody>

重新编写您的表格

<强> HTML

<table id="list">
    <thead>
        <tr>
            <th>ID</th>
            <th>User</th>
            <th>Email</th>
            <th>Summary</th>
            <th>Due Date</th>
            <th>Problem Type</th>
            <th>Status</th>
        </tr>
    </thead>
    <tbody>
        <!-- Throw stuff in here -->
    </tbody>
</table>

<强> JS

var table = $("#list");

var tr = '';

$.each(data, function(idx, elem) {
    tr += "<tr><td>" + elem.id + "</td>" + "<td>" + elem.user + 
    "</td>" + "<td>" + elem.email + "</td>" + "<td>" + elem.summary + "</td>" +
    "<td>" + elem.due_date + "</td>" + "<td>" + elem.problem_type + "</td>"+
    "<td>" + elem.status + "</td></tr>";
});

table.find('tbody').html(tr);

答案 1 :(得分:0)

$( '#列表')空(); &lt; ----你做了这个,所以整个表都是空的。

我会分开,当按钮点击时只清空

    $('#list > tbody').empty();