2015-11-30 50 views
1

說我想要一個排序數組的排序名稱的HTML列表。d3js - 如何按順序插入東西?

大多數涉及排序的d3.js示例都是通過根據排序順序定位任意排序的節點。但我需要按順序創建節點。

下面是一個問題的例子(如jsfiddle)。

var d = ['fred', 'wilma']; 
draw(d); // Gives list with 2 li elements, fred, wilma 

d.unshift('barney'); 
draw(d); // Gives 3 elements, fred, wilma, barney 

function draw(d) { 
    lis = d3.select('ul').selectAll('li').data(d, identity); 
    lis.enter().append('li').text(identity); 
} 

// just handy 
function identity(d){return d;}; 

的這個輸出是一個列表:弗雷德,威爾瑪,巴尼但我想要的清單巴尼,弗雷德,威爾瑪

我明白爲什麼這個代碼做這個(我只是用追加的容器上,所以新項目總是在最後),但有一個奇特的d3js的方式來保存數據的列表的順序?

+0

見我的回答如果是有幫助:) –

回答

0

當您對數組進行任何更改時,必須重繪整個視圖。當你使用unshift來添加一個元素時,它會被添加爲數組的第一個元素,但它不是再次重新繪製整個數組,而只是在最後添加新元素:)這裏是你可以嘗試的代碼。

var d = ['fred', 'wilma']; 

// Gives list with 2 li elements, fred, wilma 
draw(d); 

// prepend an element to our sorted list and redraw. 
window.setTimeout(function() { 
    d.unshift('barney'); 
    draw([""]); // Removing previous array to redraw. 
    draw(d); 
    console.log(d); // Print array order in console. 
}, 1000); 


function draw(d) { 
    lis = d3.select('ul').selectAll('li').data(d, identity); 
    lis.enter().append('li') 
     .text(identity) 
     .style({height:'0', overflow:'hidden'}) 
     .transition().duration(1000).style({height:'2rem'}); 
    lis.exit().remove(); // Removing previous array to redraw. 
} 

// handy 
function identity(d){return d;}; 
+0

謝謝,但是這並不完全是我正在尋找:

更新的例子。顯然這個例子很簡單 - 3個非常簡單的元素。我的用例有非常複雜的(繪製昂貴的)元素和數百個元素,所以我只想在創建新東西時創建。我需要一種方法來找到正確的位置來爲新條目插入。 – artfulrobot

+2

你可以看看'http:// stackoverflow.com/questions/17376626 /保持訂單在D3 - 數據'這是非常有幫助的答案我認爲:) –

2

那麼,事實證明這是相當無足輕重!

添加數據後,只需致電.order()即可。下面:)

var d = ['fred', 'wilma']; 
draw(d); // Gives list with 2 li elements, fred, wilma 

d.unshift('barney'); 
draw(d); // Gives 3 elements, fred, wilma, barney 

function draw(d) { 
    lis = d3.select('ul').selectAll('li').data(d, identity); 
    lis.enter().append('li').text(identity); 
    lis.order(); 
} 

// just handy 
function identity(d){return d;}; 

http://jsfiddle.net/emgjh0j7/1/

+0

[D3 V4's'Selection.order ()'documentation](https://github.com/d3/d3-selection#selection_order) - 如果你想要D3數組的排列順序按照數據數組的順序排列,你可以使用[ 'Selection.sort()'](https://github.com/d3/d3-selection#selection_sort) – user568458