如何选择与从下拉菜单中选择的名称对应的目标值。 I have a dataset在层次结构中具有以下结构:
世界有=>儿童:大陆有=>儿童国家
现在,我希望从下拉列表中选择其名称时获取各个国家/地区的值。
当我尝试我的代码时,它会返回错误
未捕获的TypeError:无法读取null的属性'target'
我认为这意味着我无法达到我需要的价值。 Js小提琴:
http://jsfiddle.net/9tnmwdyv/3/
我的代码:
function checkIt(error, root){
if (error) throw error;
var partition = d3.layout.partition()
.value(function(d) { return d.Total; });
var dropDown = d3.select("#dropdown_container")
.append("select")
.attr("class", "selection")
.attr("name", "country-list");
var options = dropDown.selectAll("option")
.data(partition.nodes(root))
.enter()
.append("option");
options.text(function (d) { var dropdownValues = d.name.replace(/[_-]/g, " ");
return dropdownValues.replace(/[_-]/g, " ") })
.attr("value", function (d) { var dropdownValues = d.name;
return dropdownValues});
function changePie() {
//get the data value and index from the event
var selectedValue = d3.event.target;
var selectedIndex = d3.event.target.selectedIndex;
//alert("You selected the option at index " + selectedIndex + ", with value attribute "+ selectedValue);
var selectedDOMElement =
d3.event.target.children[selectedIndex];
var selection = d3.select(selectedDOMElement);
//Output selected country with all its values
var uniqueData = data[selectedIndex];
console.log(uniqueData)
}
changePie();
};
d3.json("https://gist.githubusercontent.com/heenaI/cbbc5c5f49994f174376/raw/55c672bbca7991442f1209cfbbb6ded45d5e8c8e/data.json", checkIt);
答案 0 :(得分:0)
您自己调用changePie,应该将其作为事件回调调用。 d3.events.target为null,因为" d3.events"没有名为" target"的属性,它不是传递给回调的事件对象。您还可以使用"此"访问目标元素。在回调函数中,它是普通的DOM元素。如果你需要在它上面调用d3方法,只需用d3将其包装为 d3.select(this)
以下是显示事件回调的代码
d3.select(".selection").on("change", function changePie() {
console.log(this.value);
});
工作Jsfiddle:
http://jsfiddle.net/9tnmwdyv/6/
编辑*
如果要访问相应的数据,只需将分区数组保存在变量中即可访问。
var nodeArr = partition.nodes(root);
d3.select(".selection").on("change", function changePie() {
var value = this.value;
var index = this.selectedIndex;
var dataObj = nodeArr[index];
console.log(this.value + " : " + dataObj.Total + " in " + (dataObj.parent && dataObj.parent.name));
});
检查下面的Jsfiddle链接: