UndefinedError:列表对象没有未定义元素

UndefinedError: list object has no element Undefined

本文关键字:未定义 元素 对象 列表 UndefinedError      更新时间:2023-09-26

当我运行我的应用程序时,我有这个错误,我不知道问题是什么。

下面是我的html代码:

<select name="sel" onChange="myGraphFunction(this.value)">
{% for abs in absolute %}
<option value="{{abs.id|safe}}">{{abs.imp}}</option>
{% endfor %}
</select>

其中absolute是一个字典数组,如

[{'id': 1, 'imp': someName, 'd': [{'key': someKey, 'y': someValue},{'key': .., 'y': ..},...]}, {'id': 2, 'imp': .., 'd': [{...}]}, ...]

这里是我的javascript代码,我得到的值的选择,所以我可以加载一些数据:

function myGraphFunction(dd){
var testdata = {{absolute[dd].d|safe}}
nv.addGraph(function() {
var width = 500,
    height = 500;
var chart = nv.models.pieChart()
    .x(function(d) { return d.key })
    //.labelThreshold(.08)
    //.showLabels(false)
    .color(d3.scale.category10().range())
    .width(width)
    .height(height)
    .donut(true)
.labelType("percent");
chart.pie
    .startAngle(function(d) { return d.startAngle -Math.PI/2 })
    .endAngle(function(d) { return d.endAngle -Math.PI/2 });
  //chart.pie.donutLabelsOutside(true).donut(true);
  d3.select("#test2")
      //.datum(historicalBarChart)
      .datum(testdata)
    .transition().duration(1200)
      .attr('width', width)
      .attr('height', height)
      .call(chart);
nv.utils.windowResize(chart.update);
return chart;
});

当我尝试加载absolute[dd]时,问题出现了。D in testdata.

我试了这个:

if(typeof dd === 'undefined'){
var testdata = {{absolute[0].d|safe}}
}else{
var testdata = {{absolute[dd].d|safe}}
}

dd是一个Javascript名称,但是在呈现模板时它是未设置的。dd是Jinja2的Undefined对象,你的渲染失败。

您可以在函数外部设置testdata列表,然后在函数内部引用它:

var absolute = {{absolute|tojson|safe}}
function myGraphFunction(dd){
    var testdata = absolute[dd].d

我使用tojson过滤器来确保absolute被正确地转换为有效的JavaScript文字