如何在d3中使用.each?

问题描述 投票:2回答:1

你能给我解释一下为什么第一个脚本不能用吗?Firebug说 "d未定义".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>
d3.js each selectall
1个回答
0
投票

文件:

为当前选择中的每个元素调用指定的函数,传入当前的datum和index i,以及当前DOM元素的上下文。

在第一种情况下,你使用 d 不正确 -- 它指的是绑定到元素的数据,而不是元素本身。在你的例子中,你没有绑定任何数据,所以没有任何数据可以引用。

看起来你是想做以下事情。

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

这将首先把数据绑定到你正在处理的元素上 然后用绑定的数据来设置元素的属性 text.

© www.soinside.com 2019 - 2024. All rights reserved.