我有一个像这样的 Html 饼图:
//In Html:
<canvas id="pieChart" data="12,12,12,4"></canvas>
//In js:
//pie chart
var ctx = document.getElementById("pieChart");
ctx.height = 300;
var myChart = new Chart(ctx, {
type: 'pie',
data: {
datasets: [{
//data: $(this).attr("data").split(","), //This is what I want to do.
data: [45, 25, 20, 10], //This is the original code.
backgroundColor: [
"rgba(0, 123, 255,0.9)",
"rgba(0, 123, 255,0.7)",
"rgba(0, 123, 255,0.5)",
"rgba(0,0,0,0.07)"
],
hoverBackgroundColor: [
"rgba(0, 123, 255,0.9)",
"rgba(0, 123, 255,0.7)",
"rgba(0, 123, 255,0.5)",
"rgba(0,0,0,0.07)"
]
}],
labels: [
"green",
"green",
"green"
]
},
options: {
responsive: true
}
});
代码 $(this).attr("data").split(",") 引发错误:
Cannot read property 'split' of undefined
那么,如何获取“data”的值呢? 谢谢。
<小时/>答案是ctx.getAttribute('data')。 谢谢你们的帮助:)
最佳答案
您不应该使用 this
,它会返回错误,因为它引用的是 Chart
,而不是 HTML 节点。
由于您已经有了针对该节点的 ctx 变量,因此我建议您使用它。那么,有两种可能:
- 在 native JavaScript 中的
ctx
元素上使用.getAttribute(…)
(您不需要需要 jQuery), - 如果您更喜欢使用 jQuery,也可以使用
$(ctx).attr(…)
。
片段
//pie chart
var ctx = document.getElementById("pieChart");
ctx.height = 300;
var myChart = new Chart(ctx, {
type: 'pie',
data: {
datasets: [{
data: ctx.getAttribute("data").split(","), // Here is how you can do it without jQuery !…
// data: $(ctx).attr("data").split(","), // … And with jQuery !
backgroundColor: [
"rgba(0, 123, 255,0.9)",
"rgba(0, 123, 255,0.7)",
"rgba(0, 123, 255,0.5)",
"rgba(0,0,0,0.07)"
],
hoverBackgroundColor: [
"rgba(0, 123, 255,0.9)",
"rgba(0, 123, 255,0.7)",
"rgba(0, 123, 255,0.5)",
"rgba(0,0,0,0.07)"
]
}],
labels: [
"green",
"green",
"green"
]
},
options: {
responsive: true
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.7.2/Chart.bundle.js"></script>
<canvas id="pieChart" data="12,12,12,4"></canvas>
关于jquery - jquery如何获取元素的属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51880259/