【发布时间】:2018-01-30 11:45:12
【问题描述】:
我有几个 morris.js 图表,这些图表根据某些搜索词从我的数据库中填充。我使用以下代码为 mmy 甜甜圈图构建“图例”。代码工作正常,但我在添加数字和文本时遇到了困难,我收到控制台错误:“ReferenceError:未定义值,这是我当前使用的代码(效果很好):
// Build the Donut:
var donut = Morris.Donut({
element: 'donut',
data : donutParts,
colors: color_array
});
// Build the Legend:
donut.options.data.forEach(function(label, i){
var legendItem = $('<span></span>').text(label['label']).prepend('<i> </i>');
legendItem.find('i').css('backgroundColor', donut.options.colors[i]);
$('#legend').append(legendItem)
})
这将为我提供一个带有匹配颜色方块和适当标签的图例,例如:
[red] UK
但我想要:
[red] # UK
我尝试过使用.integer 和其他类似的变体:
// Build the Donut:
var donut = Morris.Donut({
element: 'donut',
data : donutParts,
colors: color_array
});
// Build the Legend:
donut.options.data.forEach(function(label, i){
var legendItem = $('<span></span>').text(label['label']).integer(['value']).prepend('<i> </i>');
legendItem.find('i').css('backgroundColor', donut.options.colors[i]);
$('#legend').append(legendItem)
})
但这给了我未定义值的错误,我想从donutParts 获取value(v)
这是我的 donutParts 变量:
// Fetch the data to populate the donut chart:
var chartData = JSON.parse( $('#chartData').val() );
// Break up the object into parts of the donut:
var donutParts = [];
$.each( chartData, function(k,v){
donutParts.push({
label: k,
value: v
});
});
有什么帮助吗?干杯!
***** 答案 ***** 以下代码给出了所需的输出:
// Build the Legend:
donut.options.data.forEach(function(label, i){
var legendItem = $('<span></span>').text(label['value']+" "+label['label']).prepend('<i> </i>');
legendItem.find('i').css('backgroundColor', donut.options.colors[i]);
$('#legend').append(legendItem)
})
非常感谢@WillParky93
【问题讨论】:
-
您使用的代码基本上是在说
"Get something within <span></span> that has label of "label" then add at the end of it some <i> tags. Once added the <i> tags, attach a background colour to it"所以考虑到这一点,您尝试用 .integer(['value']) 做什么是没有意义的。我不太擅长 jquery,但我会试一试。您尝试分配的值是什么? -
我对 jquery 也不是很好,我打算参加一些课程哈哈,不过感谢您的回答,我会将我的 donutParts 变量添加到我的问题中
-
我的 i 标签也位于每个标签的前面,并使用 css 进行样式设置:) 图例有效,但我无法获得数字。不是真的需要,但它会是一个很好的接触
-
您能否发布(在 OP 中)这些元素之一的输出
标签: javascript php jquery foreach morris.js