jQuery替换表正文内容

j3f*_*ffz 14 jquery

我似乎遇到了我的jQuery脚本问题.我想用新的"tbody"内容替换当前的"tbody"内容.目前,它只是继续添加到当前数据,而不是删除旧数据和插入新数据.有任何想法吗?

这是我的代码:

function getData(action,searchVal) {    
    $.get('ajax.php',{action:action,value:searchVal}, function(data){
        var json = jQuery.parseJSON(data);
        $(function () {
            var content = '';
            content += '<tbody>';
            for (var i = 0; i < json.length; i++) {
            content += '<tr id="' + json[i].ID + '">';
            content += '<td><input id="check_' + json[i].ID + '" name="check_' + json[i].ID + '" type="checkbox" value="' + json[i].ID + '" autocomplete=OFF /></td>';
            content += '<td>' + json[i].ID + '</td>';
            content += '<td>' + json[i].Name + '</td>';
            content += '<td>' + json[i].CountryCode + '</td>';
            content += '<td>' + json[i].District + '</td>';
            content += '<td>' + json[i].Population + '</td>';
            content += '<td><a href="#" class="edit">Edit</a> <a href="#" class="delete">Delete</a></td>';
            content += '</tr>';
            }
            content += '</tbody>';
            $('table tbody').replaceWith(content);  
       });  
    });
};
Run Code Online (Sandbox Code Playgroud)

Fat*_*orm 38

function getData(action,searchVal) {    
    $.get('ajax.php',{action:action,value:searchVal}, function(data){
        var json = jQuery.parseJSON(data);
        $(function () {
            var content = '';
            //content += '<tbody>'; -- **superfluous**
            for (var i = 0; i < json.length; i++) {
            content += '<tr id="' + json[i].ID + '">';
            content += '<td><input id="check_' + json[i].ID + '" name="check_' + json[i].ID + '" type="checkbox" value="' + json[i].ID + '" autocomplete=OFF /></td>';
            content += '<td>' + json[i].ID + '</td>';
            content += '<td>' + json[i].Name + '</td>';
            content += '<td>' + json[i].CountryCode + '</td>';
            content += '<td>' + json[i].District + '</td>';
            content += '<td>' + json[i].Population + '</td>';
            content += '<td><a href="#" class="edit">Edit</a> <a href="#" class="delete">Delete</a></td>';
            content += '</tr>';
            }
           // content += '</tbody>';-- **superfluous**
            //$('table tbody').replaceWith(content);  **incorrect..**
             $('#myTable tbody').html(content);  // **better. give the table a ID, and replace**
       });  
    });
};
Run Code Online (Sandbox Code Playgroud)

如果您没有学会正确定位替换,则可能最终会有多个表并替换两者的内容.因为你要替换tbody内容,你不能在其内部添加另一个级别的tbody ...