我想刪除單擊的欄,但出於某種原因,它總是刪除最後一個欄。我認爲答案可能在以下文章(http://pothibo.com/2013/09/d3-js-how-to-handle-dynamic-json-data/)中,但我不確定是否需要手動爲每個元素分配鍵。我花了幾個小時試圖讓這個工作,所以我希望有人能指出我在正確的方向。提前致謝。刪除不正確的SVG組
<html>
<head>
<title>Interactive Div-based Bar Chart</title>
<style type="text/css">
.chart rect {
fill: teal;
}
.chart text {
fill: white;
font: 30px sans-serif;
text-anchor: end;
}
</style>
<script src="Scripts/d3.min.js"></script>
</head>
<body>
<div id="data-field"></div>
<button id="add-btn">Add Data</button>
<p>Click on a bar to remove it</p>
<script>
var barHeight = 75, margin = 3, padding = 3;
var chartData = [6,12,15,21,29,41];
var chart = d3.select("body").append("svg").attr("class","chart");
drawChart();
function drawChart() {
var selection = chart.selectAll("g")
.data(chartData);
// Remove extra bars
selection.exit()
.remove();
// Add more bars
var groups = selection.enter()
.append("g");
var bars = groups
.append("rect");
var labels = groups
.append("text");
// Update existing bars
groups
.attr("transform", function (d, i) { return "translate(0," + i * (barHeight + margin) + ")"; })
.on("click", function (d, i) { chartData.splice(i, 1); drawChart(); });
bars
.attr("width", function (d) { return d * 10 + "px"; })
.attr("height", barHeight);
labels
.attr("x", function (d) { return d * 10 - padding + "px"; })
.attr("y", barHeight/3 + padding + "px")
.text(function (d) { return d; });
// update list of numbers
d3.select("#data-field").text("numbers: [" + chartData.join(", ") + "]");
}
// add more data
d3.select("#add-btn")
.on("click", function(d) { chartData.push(Math.round(Math.random() * 100)); drawChart(); });
</script>
</body>
</html>
plz put in fddle – 2014-10-11 03:28:24
http://jsfiddle.net/zxg02fdm/1/ – loucatsfan 2014-10-14 13:50:05