Javascript 如何从内部json数组中获取目标值

Javascript 如何从内部json数组中获取目标值,javascript,json,d3.js,Javascript,Json,D3.js,如何选择与从下拉菜单中选择的名称相对应的目标值。在具有以下结构的层次结构中: 世界有=>儿童:大陆有=>儿童国家 现在我想从下拉列表中选择某个国家的名称时,获取该国家的值 当我尝试我的代码时,它返回错误 未捕获类型错误:无法读取null的属性“target” 我想这意味着我无法获得我需要的价值观。 Js小提琴: 我的代码: function checkIt(error, root){ if (error) throw error; var partition = d3.la

如何选择与从下拉菜单中选择的名称相对应的目标值。在具有以下结构的层次结构中:

世界有=>儿童:大陆有=>儿童国家

现在我想从下拉列表中选择某个国家的名称时,获取该国家的值

当我尝试我的代码时,它返回错误

未捕获类型错误:无法读取null的属性“target”

我想这意味着我无法获得我需要的价值观。 Js小提琴:

我的代码:

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);

您自己正在调用changePie,它应该作为事件回调调用。d3.events.target为null,因为“d3.events”没有名为“target”的属性,它不是传递给回调的事件对象。您还可以在回调函数中使用“this”访问目标元素,它是纯DOM元素。如果您需要在其上调用d3方法,只需使用d3将其包装为d3。选择(this)

下面是显示事件回调的代码

d3.select(".selection").on("change", function changePie() {
    console.log(this.value);
});
工作区:

编辑*

如果要访问相应的数据,只需将分区数组保存在变量中并访问它即可

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));
});
检查下面的JSFIDLE链接:


你说得对,但console.log(此值)给出了国家的名称,而我想要的是与所选国家相对应的数据集中的数据更新了我的答案以获取所选选项的数据。