[英]D3 data not updating
我正在嘗試學習d3的一些基本概念,但是在更新已經綁定到html元素的數據時,我陷入了困境。
我創建了一個js小提琴來展示問題jfiddle
我正在嘗試做的是創建一個條形圖,該條形圖的全寬度約為860px,上面還有其他幾個條形圖。 這些其他條的寬度即為條總寬度的百分比。
因此,此條是根據我傳遞給第一個d3聯接的數據生成的。 我想用不同大小的新條形更新此數據,但是每次嘗試添加新項時,圖形都會縮小為僅顯示新條形。
我沒有使用svg來渲染我的欄,我仍在學習基礎知識,但是這里是代碼:
var x = d3.scale.linear()
.domain( [ 0, d3.max( percents, function ( d ) {
return d.percent
} ) ] )
.range( [ 0, chartRange ] );
chart.selectAll( 'div' ) // Creates an empty selection of divs
.data( percents, function ( d, i ) {
// Joins the specified array of data with the current selection
return d.percent;
} )
.enter().append( 'div' )
.style( 'width', function ( d ) {
return x( d.percent ) + 'px';
} )
.style( {
'height': '20px'
} )
.style( 'z-index', function ( d, i ) {
return percents.length - i;
} )
.style( {
'border-right': '2px dotted #00D0BC'
} )
.style( {
'text-align': 'right'
} )
.append( 'p' )
.text( function ( d ) {
return d.num * 10;
} );
var percents = [
{
num: 0,
percent: 0,
changed: false
},
{
num: 30,
percent: 0,
changed: false
},
{
num: 50,
percent: 0,
changed: false
},
{
num: 70,
percent: 0,
changed: false
},
{
num: 90,
percent: 0,
changed: false
},
{
num: 100,
percent: 0,
changed: false
}
];
您必須再次手動調用D3,並告訴它重新呈現您的數據。 這是通過再次重新綁定數據來完成的。
因此,將您的“繪圖”功能封裝到如下功能中:
function renderData(percents) {
chart.selectAll('div') // Creates an empty selection of divs
.data(percents, function (d, i) {
// Joins the specified array of data with the current selection
return d.percent;
})
.enter().append('div')
.style('width', function (d) {
return x(d.percent) + 'px';
})
.style({
'height': '20px'
})
.style('z-index', function (d, i) {
return percents.length - i;
})
.style({
'border-right': '2px dotted #00D0BC'
})
.style({
'text-align': 'right'
})
.append('p')
.text(function (d) {
return d.num * 10;
});
}
每次更改數據時,只需再次調用renderData(percents)
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.