[英]d3 data update CSV - can't figure out how to update table cells
我有一個haproxy status端點,它輸出以下數據:
我想解析它的輸出並構建一個不錯的交互式儀表板(在這種情況下,在給定時間監視哪個Riak節點處於打開或關閉狀態。
我寫了以下內容:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>dadsa</title>
</head>
<body>
<div id="viz"></div>
<script src="//d3js.org/d3.v3.min.js" charset="utf-8"></script>
<script>
var hosts = [];
var url = "http://localhost:8666/haproxy-csv";
function update() {
d3.csv(url, function(data) {
hosts = data.filter(
function(d){
console.log(JSON.stringify( d) );
console.log(Object.keys(d));
console.log(d["# pxname"]);
return d["# pxname"] == "riak_backend_http"
&& d["svname"] != "BACKEND";
}
).map(function(d){
return {"label": d["svname"],"value": d["status"]};
});
d3.select("#viz")
.append("table")
.style("border-collapse", "collapse")
.style("border", "2px black solid")
.selectAll("tr")
.data(hosts)
.enter().append("tr")
.selectAll("td")
.data(function(d){
return [
d["label"], d["value"]
];
})
.enter().append("td")
.style("border", "1px black solid")
.style("padding", "5px")
.on("mouseover", function(){d3.select(this).style("background-color", "aliceblue")})
.on("mouseout", function(){d3.select(this).style("background-color", "white")})
.text(function(d){return d;})
.style("font-size", "12px");
});
}
update();
setInterval(update, 1000);
</script>
<button onclick="alert(JSON.stringify(hosts[0]))"> see value </button>
<div id="svg"/>
</body>
</html>
該代碼運行良好,但有一個小缺陷。它在每次更新時都不斷添加新的表格元素。 我已經多次重寫了這段代碼,但是無論我寫什么,似乎都只會更新一次。
這是當前輸出的樣子:
我真的對d3一無所知,所以甚至不確定我應該綁定或迷上什么。
有指針嗎?
您每次更新都會得到一個新表,因為每次在update函數中執行此操作時,實際上每次都會附加一個新表。
...
d3.select("#viz")
.append("table")
...
而是通過HTML標記或使用javascript預先創建表。 在更新功能之外創建它。 說像這樣:
var myTable = d3.select("#viz")
.append("table")
.style("border-collapse", "collapse")
.style("border", "2px black solid");
現在您已經設置了表,我們可以使用enter(),exit()和update()的“ D3.js方式”對其進行更新,如下所示:
//bind the data to rows
var rows = myTable.selectAll("tr").data(hosts);
//append as needed using enter()
rows.enter().append("tr");
//remove placeholders in exit
rows.exit().remove();
//bind the data to columns in each row
var columns = myTable.selectAll("tr")
.selectAll("td")
.data(function(d){
return [
d["label"], d["value"]
];
});
//enter and exit as above
columns.enter().append("td");
columns.exit().remove();
//finally update the columns
myTable.selectAll("td")
.style("border", "1px black solid")
.style("padding", "5px")
.on("mouseover", function(){d3.select(this).style("background-color", "aliceblue")})
.on("mouseout", function(){d3.select(this).style("background-color", "white")})
.text(function(d){return d;})
.style("font-size", "12px");
希望這可以幫助。
為什么不刪除每次更新中的表元素。 添加此行
d3.csv(url, function(data) {
d3.select("#viz").select("table").remove();//removes the table
//other code as usual
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.