如何通过jQuery获取元素的属性

时间:2018-08-16 15:08:37

标签: jquery chart.js attr

我有一个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

那么,如何获取“数据”的值? 谢谢。


答案是ctx.getAttribute('data')。 谢谢你们:)

2 个答案:

答案 0 :(得分:2)

您不应该使用this,它返回一个错误,因为它引用的是Chart,而不是HTML节点。

由于您已经有了针对该节点的ctx变量,因此建议您使用它。然后,有两种可能性:

  • 在本机JavaScript中的.getAttribute(…)元素上使用ctx(不需要 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>

答案 1 :(得分:1)

首先,您应该使用data-*语法。

https://developer.mozilla.org/en-US/docs/Learn/HTML/Howto/Use_data_attributes

第二个:

我会说ctx.getAttribute('data')是您的解决办法?

但是,请将data属性更改为其他内容。 (数据集...):)