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

How to get an attribute of element by jquery

我有一个这样的 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')。 谢谢你们 :)

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

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

第二个:

我会说 ctx.getAttribute('data') 是你的解决方案吗?

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

你不应该使用 this,它 returns 是一个错误,因为它指的是 Chart,而不是 HTML 节点。

因为您已经有了针对节点的 ctx 变量,我建议您使用它。那么,有2种可能:

  • 在原生 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>