d3.js无法更新数据绑定

d3.js无法更新数据绑定,d3.js,D3.js,绝对是d3.js的新手 我正在尝试一个教程,从它应该是直接向前,但我正在拔我的头发了 <!DOCTYPE html> <html> <head> <script type="text/javascript" src="https://d3js.org/d3.v6.min.js"></script> </head> <style>

绝对是d3.js的新手

我正在尝试一个教程,从它应该是直接向前,但我正在拔我的头发了

<!DOCTYPE html>
<html>
    <head>
        <script type="text/javascript" src="https://d3js.org/d3.v6.min.js"></script>
    </head>
    <style>
        body {font-family: Arial;}
    </style>
    <body>
        <ul id="list">
            <li></li>
            <li></li>
        </ul>
        <input type="button" name="load" value="Load List" onclick="javascript:load()"/>
        <input type="button" name="remove" value="Remove Fourth Value" onclick="javascript:remove()"/>
        <script>
            function load() {
                d3.select("#list").selectAll("li")
                .data([10,20,30,25,15])
                .text(function(d){console.log(d); return "This is pre-existing element and the value is " + d;})
                .enter()
                .append("li")
                .text(function(d){return "This is dynamically created element and the value is "+d;})
            }
            function remove() {
                d3.select("#list").selectAll("li")
                    .data([10,30,25,15])
                    .exit()
                    .remove()
            }
        </script>
    </body>
</html>

正文{字体系列:Arial;}
函数加载(){ d3.选择(“列表”)。选择全部(“li”) .数据([10,20,30,25,15]) .text(函数(d){console.log(d);返回“这是预先存在的元素,值为”+d;}) .输入() .附加(“li”) .text(函数(d){return“这是动态创建的元素,值为“+d;}”) } 函数删除(){ d3.选择(“列表”)。选择全部(“li”) .数据([10,30,25,15]) .exit() .删除() }
HTML页面将加载两个空的预定义项目符号。列表将在您单击“加载”按钮后生成,这一切都很好。我不太理解的逻辑是“remove()”函数,通过提供新版本的数据,d3.js不应该删除列表中的第二项吗?相反,它总是删除列表上的最后一项,就好像更新是基于传递给.data()的数组的大小而不是实际值一样

事实上,原来的教程并不像它描述的那样工作。但是.exit()和.remove()应该将现有数据与给定的新数据进行比较,并删除新数据中遗漏的数据


谢谢你的帮助。提前谢谢

.data([10,30,25,15],d=>d)
。解释一下:@GerardoFurtado谢谢!现在它就像一个符咒
.data([10,30,25,15],d=>d)
。解释一下:@GerardoFurtado谢谢!现在它就像一个符咒!