2 回答

TA貢獻1820條經驗 獲得超9個贊
訪問您的行的正確方法是函數內的 d3.select(this) 。d 參數是連接的數據。我不知道是否有更好的迭代方法,但 .each 函數對我有用。
以下是https://www.d3indepth.com/selections/中 .each 的示例用法:
function addNumberedCircle(d, i) {
d3.select(this)
.append('circle')
.attr('r', 40);
d3.select(this)
.append('text')
.text(i + 1)
.attr('y', 50)
.attr('x', 30);
}
d3.selectAll('g.item')
.each(addNumberedCircle);

TA貢獻1876條經驗 獲得超7個贊
文檔說 .each 函數的三個參數是 (1) 數據,(2) 當前索引,以及 (3) 選擇中的節點。https://github.com/d3/d3-selection/blob/v1.4.1/README.md#selection_each
在這里提供一個答案,以防萬一有人想使用 ES6 箭頭函數,或者他們在使用已接受答案中使用的“this”關鍵字時遇到問題。
在每個函數中選擇元素時使用“this”很好,但我在 SPA 應用程序中使用“this”時遇到了問題,其中“this”通常意味著其他含義,可能會讓人感到困惑。
為避免使用“this”,可以將代碼更改為:
d3.select('svgEditor').selectAll('line').each(function(d,i){
d3.select(this).append.....
});
到:
d3.select('svgEditor').selectAll('line').each((data, i, nodes) => {
d3.select(nodes[i]).append....
});
這篇文章有助于解釋https://medium.com/@yonester/on-d3-and-arrow-functions-b6559c1cebb8
添加回答
舉報