jQuery 替换表格正文内容
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4453145/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
jQuery Replace Table Body Contents
提问by j3ffz
I seem to be having problems with my jQuery script. I would like to replace the current "tbody" contents with the new "tbody" contents. Currently it is just continues to add to the current data instead of removing the old data and inserting the new data. Any ideas?
我的 jQuery 脚本似乎有问题。我想用新的“tbody”内容替换当前的“tbody”内容。目前它只是继续添加到当前数据,而不是删除旧数据并插入新数据。有任何想法吗?
Here is my code:
这是我的代码:
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);
});
});
};
回答by FatherStorm
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**
});
});
};
If you don't learn to correctly target your replace, you might end up with more than one table and replace the content of both. also since you are replacing the tbody contents, you can't add another level of tbody inside itself...
如果你没有学会正确定位你的替换,你最终可能会得到多个表并替换两者的内容。此外,由于您正在替换 tbody 内容,因此您无法在其内部添加另一个级别的 tbody ......
回答by Mad Dog
Probably doesn't help so long after the post, you've probably retired, but here's my 2 cents worth.
发布后可能不会有多大帮助,您可能已经退休了,但这是我的 2 美分。
I removethe tbody from the targettable like so. $("#table_contacts tbody").remove();
我像这样从目标表中删除了 tbody 。$("#table_contacts tbody").remove();
Then use the following code to build an array of items containing a table row and corresponding cells, which are then appended to a tbody element which is in turn appended to the target table. The grunt work building the table row is abstracted to a separate function, buildItemRow(), for the sake of clarity.
然后使用以下代码构建一个包含表格行和相应单元格的项目数组,然后将其附加到 tbody 元素,该元素又附加到目标表。为清晰起见,构建表行的繁重工作被抽象为单独的函数 buildItemRow()。
$.getJSON(uri)
// On success, 'data' contains a list of employees.
.done(function (data) {
// build table rows and cells for passed employee
$.each(data, function (key, item) {
items.push(buildItemRow(item));
});
$('<tbody/>', {
html: items.join('')
}).appendTo('#table_contacts');
})
.fail(function (jqXHR, textStatus, err) {
$('#messages').toggleClass('badmessage');
$('#messages').html('A system error occurred while processing the request: ' + err + '<br />' + 'System Message: ' + jqXHR.responseText);
});
回答by greg.arnott
this.find('tbody').empty().append(content);
Can be enough to make it work if the correct table is passed.
如果通过了正确的表,就足以让它工作。
Otherwise, get a little designer and have customisation like this:
否则,请一个小设计师并进行如下定制:
var UDT = {
proc : function(selector, settings) {
// settings - set defaults
var config = {
'sortable': false,
'pagination': false,
'action': 'get',
'searchVal': 'location'
};
if ( settings ){$.extend(config, settings);}
var obj = $(selector);
$.get('ajax.php',{action:action,value:searchVal}, UDT.sortShowData(data,obj));
if (config.sortable) {obj.children('thead').find('th').addClass('sort');}
if (config.pagination) {UDT.pageTable(obj);}
},
sortShowData : function(data,obj) {
var json = jQuery.parseJSON(data);
var content = '';
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>';
}
obj.find('tbody').empty().append(content);
},
pageTable : function(obj) {
// get content region for table height, tr height - work out how many rows can fit etc
// else maxrows value
// create tfoot content and append/replace to table
}
};
// call for UpDateTable
UDT.proc($(##target_table##),{sortable:true, pagination:true, ...});
btw - adlibbed code... should work, but battery warning kicking in.
顺便说一句 - adlibbed 代码......应该可以工作,但是电池警告开始了。
回答by Darwin
I often encounter such behavior (mostly when using jQuery table-sorting plugins), and finally started keeping whole table contents in a variable (header basically and adding dynamic content as strings) and adding it like this:
我经常遇到这样的行为(主要是在使用 jQuery 表格排序插件时),最后开始将整个表格内容保存在一个变量中(基本上是标题并将动态内容添加为字符串)并像这样添加它:
$("div_containing_the_table").html(table_content)
$("div_containing_the_table").html(table_content)
or
或者
div_containing_the_table.innerHTML = table_content
div_containing_the_table.innerHTML = table_content
Even if it works, changing 'tbody' content on the fly doesn't seem to be the practice to rely on.
即使它有效,动态更改“tbody”内容似乎也不是可以依赖的做法。
回答by jjsanabria
I had the same issue but it was a very stupid thing. When I looked at the page source my markup was something like this:
我有同样的问题,但这是一件非常愚蠢的事情。当我查看页面源代码时,我的标记是这样的:
<table>
<thead>
<th> 1 </th>
<th> 2 </th>
<th> 3 </th>
</thead>
<tbody> </tbody>
<tr> bla </tr>
<tr> bla </tr>
<tr> bla </tr>
</table>
This occurred due to an indentation typo en Jade...Obviously I was getting a duplicate table. Just a quick reminder...check the markup first!!!
这是由于 Jade 中的缩进错字造成的……显然我得到了一个重复的表。只是一个快速提醒...首先检查标记!