我正在尝试向 Chart JS 数据集添加额外的属性(对于饼图/圆环图)。我在后端有一段 Ruby,可以将以下 JSON 打印到 View 中:
[
{"segment": "undetermined",
"label": "Undetermined",
"value": 420193,"
color": "#DECF3F",
"highlight": "#e2d455"
},
{"segment":"peer_review",
"label":"Peer Review",
"value":415212,
"color":"#60BD68",
"highlight":"#72c479"
}
]
“segment”属性是我想在前端的 JS 中使用的附加属性(库未提供)。但是,当我将此 JSON 包装在 canvas
标记中时,我无法通过 JS 访问它。
下面第二行输出上述 JSON:
<canvas id="review-type" height="235" data-facet="review_status_s">
<%= @by_review_type %>
</canvas>
我正在尝试使用 getSegmentsAtEvent()
API 调用访问“segment”属性(名称冲突意外):
$("#review-type").click(
function(evt) {
var activePoints = reviewChart.getSegmentsAtEvent(evt);
/* extract other properties, then build an URL from them: */
var url = "/" +locale+ "/catalog?f[" +facet_frag+ "][]=" +segment+ "&q=*:*";
window.location = url;
}
);
但是,当我在 JS 控制台中检查 activePoints
时,“segment”不在属性列表中。
我应该做什么?
最佳答案
getSegmentsAtEvent
(及其其他图表类型的等效项)返回图表元素(扇区、点、条形等)。您必须使用任何图表元素属性和数据对象来找出索引,然后使用它来获取所需的附加属性。
例如,如果 pieData
是您的数据对象
$("#review-type").click(
function (evt) {
var activePoints = reviewChart.getSegmentsAtEvent(evt);
if (activePoints.length)
alert(pieData.filter(function (e) { return e.label === activePoints[0].label; })[0].segment);
...
您还可以在从对象传输到元素的属性上设置其他属性(例如 label
),但这有点hacky。
fiddle - http://jsfiddle.net/nm9ay728/
关于javascript - 向 Chart JS 数据集添加其他属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36717918/