I'm using DataTable API and jquery to construct a table after getting its rows from the server. Then I press the btn to load other rows and add the to the end of the table. The trouble is when I hide certain columns: the initial rows get rid of triggered columns but those which are loaded later aren't affected by filters. How to fix this? After research I found out that when filtering the function gets all the rows not the initial ones.
var data = $(this).dataTable().toArray();
if ($this.prop("checked") === false) {
data.forEach(function (element) {
$(element).DataTable().columns().column(column).visible(false);
});
} else {
data.forEach(function (element) {
$(element).DataTable().columns().column(column).visible(true);
});
}
Loading the remaining rows
var tbody = $("#tbody-" + $this.attr("data-parent-id"));
var dt = tbody.parents(".bizon-datatable").DataTable();
$(result).filter("tr").each(function (i, v) {
dt.row.add($(v));
});
tbody.append(result);
The key is understanding that each
executes against the set of items that are found at the moment that selector runs . So if you have 10 rows initially and each
executes, it will apply to 10 rows, and any added later will not have the conditions applied by each
.
The same goes for filter
. It applies to the elements that are returned by the selector at the time the selector executes--not to anything added later. The selector only selects DOM elements that match at the moment it runs and doesn't apply to any future DOM elements that are added. So you have to re-select DOM elements after you've added elements if you want to apply filters or other conditions to all current DOM elements.
To fix this, you would need to re-apply the filter
after adding rows or re-run the each
if you have added rows.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.