如何在 d3 中使用 .each?

How to use .each in d3?

你能解释一下为什么第一个脚本不起作用吗? Firebug 表示 "d is undefined"。 val是selectall后的二维数组

<script type="text/javascript">
        setInterval(function() {
            d3.json("./cgi-bin/script1.sh?shmid=" + node.value, function(error, txt){
                if (error) return console.warn(error);

                table = d3.select("#shmid" + node.value);
                val = table.selectAll(".val")

                val.each(function(d,i){
                    console.debug(d,i)
                    d.text(txt.bd[i].val);
                });

                node = node.next;
            })
        }, 500);

    </script>

工作变体:

<script type="text/javascript">
        setInterval(function() {
            d3.json("./cgi-bin/script1.sh?shmid=" + node.value, function(error, txt){
                if (error) return console.warn(error);

                table = d3.select("#shmid" + node.value);
                val = table.selectAll(".val")

                val.each(function(d,i){
                    console.debug(d,i)
                    d3.select(this).text(txt.bd[i].val);
                });

                node = node.next;
            })
        }, 500);

    </script>

来自the documentation

Invokes the specified function for each element in the current selection, passing in the current datum d and index i, with the this context of the current DOM element.

在第一种情况下,您错误地使用了 d -- 它指的是绑定到元素的数据,而不是元素本身。在你的情况下,你没有绑定任何数据,所以没有什么可参考的。

您似乎正在尝试执行以下操作:

table = d3.select("#shmid" + node.value);
table.selectAll(".val").data(txt.bd)
     .text(function(d) { return d.val; });

这将首先将数据绑定到您正在使用的元素,然后使用绑定的数据设置 text