我正在尝试设置两个下拉菜单。菜单中的选项源自嵌套数据集。在第一个菜单(group1)中选择的选项将确定第二个菜单(group2)中可用选项的范围。在第一个或第二个菜单中选择选项应导致图表更新。
第二个菜单选择未正确更新。在group1菜单中进行选择时,group2菜单中的选项不会更改,除非新菜单选项的选项多于上一个菜单选项,在这种情况下,extra2菜单会附加额外的选项。
我不确定为什么这不起作用。我对应用于菜单选项的数据绑定/更新的理解可能是错误的。怎么能这样做?
我设置了这样的菜单:
// Set up the group1 selection menu
var select1 = d3.select("#chart")
.append("select")
.attr("class", "select")
.attr("id", "select1")
.on("change", function() { // If the group1 selection changes, change the options for group2 menu, and also update the graph?
// Join the new options with previous data
var options2 = d3.select("#select2").selectAll("option")
.data(); // new options for group2 menu from the nested data
// Remove exit selection
options2.exit().remove();
// Update selection
options2.enter().append("option")
.text(function(d) { return d; });
});
// Options for group1 selection menu
var options1 = d3.select("#select1")
.data(); // Options for group1 from the nested data
.append("option")
.text(function (d) { return d; });
// Set up the initial group1 selection menu
var select2 = d3.select("#chart")
.append("select")
.attr("class", "select")
.attr("id", "select2")
.on("change", onchange);
// Initial options for group2 selection menu
var options2 = d3.select("#select2")
.selectAll("option")
.data() // initial options for group2
.append("option")
.text(function(d) { return d; });
function onchange() {
// Make a graph with the selected data
}
答案 0 :(得分:1)
这是D3 v4,而不是v3。在D3 v4中,删除了输入选择的“magic”,它将输入的元素复制到更新选择中。
因此,您必须merge选择:
options2.enter()
.append("option")
.merge(options2)//merging here
.text(function(d) {
return d;
});
要获得更好的解释,请查看我的answer here。
以下是只有1行更改的plunker:http://plnkr.co/edit/APN2HqI1MY5KQb65qCHt?p=preview