问题
i have following code,i have to add pagination on this table
<!DOCTYPE html>
<html>
<head>
<title>table</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.4.11/d3.min.js"></script>
<style>
.rect {
outline: 1px solid green;
}
</style>
</head>
<body>
<div id="table"></div>
<script>
var data = [{
"name": "a",
"section": 1,
"stars": "d1"
}, {
"name": "b",
"section": 2,
"stars": "d2"
}, {
"name": "c",
"section": 1,
"stars": "d3"
}];
var columns = ['name', 'section', 'stars']
// create table
var table = d3.select("#table").append("table");
var thead = table.append("thead").append("tr");
thead.selectAll("th")
.data(columns)
.enter()
.append("th")
.text(function(d) {
return d;
});
var tbody = table.append("tbody");
data.forEach(function(d, i) {
trow = tbody.append("tr")
trow.selectAll("td")
.data(columns)
.enter()
.append("td")
.append(function(d) {
if (d == "stars") {
return document.createElement('button');
} else
return document.createElement('div');
})
.attr("class", function(d) {
if (d == "section") {
return "rect"
}
})
.text(function(e) {
return d[e]
});
});
</script>
</body>
</html>
how to add pagination in d3? i have to set pagination for each two rows,please suggest the solution. just i have added 3 rows of data but my actual data contains 50 to 100 rows
回答1:
At the simplest level you just control the visibility/display of the table rows. This example is as basic as you get , it uses two buttons to show different groups of ten in a table - no page numbering, no limiting, no styling :-) - but it does the pagination
http://jsfiddle.net/f50mggof/6/
<div id="buttons">
<button id="up">
UP
</button>
<button id="down">
DOWN
</button>
</div>
<table></table>
var dataset = [];
for (var n = 0; n < 100; n++) {
dataset.push ([n, Math.random()*50, Math.random()*30]);
}
var rows = d3.select("table").selectAll("tr").data(dataset)
.enter()
.append("tr")
;
var cells = rows.selectAll("td").data(function(d) { return d; })
.enter()
.append("td")
.text(function(d) { return d; })
;
d3.select("#buttons").datum({portion : 0});
// the chain select here pushes the datum onto the up and down buttons also
d3.select("#buttons").select("#up").on ("click", function(d) {
d.portion -= 10;
redraw (d.portion);
});
d3.select("#buttons").select("#down").on ("click", function(d) {
d.portion += 10;
redraw (d.portion);
})
function redraw (start) {
d3.select("table").selectAll("tr")
.style("display", function(d,i) {
return i >= start && i < start + 10 ? null : "none";
})
}
redraw(0);
来源:https://stackoverflow.com/questions/37615512/how-to-add-pagination-in-table-using-d3