简体   繁体   中英

Set HTML attribute as JSON object using jQuery

I am trying to set the attribute of an HTML canvas element, but the attribute has a value, which should be an array. How should it be done? Please help.

JavaScript:

var labels = ["January", "February", "March", "April", "May", "June", "July"];
var series = ['Series A', 'Series B'];
var data = [
  [65, 59, 80, 81, 56, 55, 40],
  [28, 48, 40, 19, 86, 27, 90]
];
var datasetOverride = [{yAxisID: 'y-axis-1'}, {yAxisID: 'y-axis-2'}];
var options = {
  scales: {
    yAxes: [{
        id: 'y-axis-1',
        type: 'linear',
        display: true,
        position: 'left'
      },
      {
        id: 'y-axis-2',
        type: 'linear',
        display: true,
        position: 'right'
      }
    ]
  }
};

Trying to set attribute:

$('#line').attr("chart-data", data);
$('#line').attr("chart-labels", labels);
$('#line').attr("chart-series", series);
$('#line').attr("chart-options", datasetOverride );
$('#line').attr("chart-dataset-override", options);

HTML:

<canvas id="line" class="chart chart-line"></canvas>

You can do this in many ways. One of them is convert them to a string with join. Like this:

 var data = [ [65, 59, 80, 81, 56, 55, 40], [28, 48, 40, 19, 86, 27, 90] ]; var joined = data.join(','); console.log(joined); $('#line').attr("chart-data", joined); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div id="line">line</div> 

Please inspect the div element. I used a div, so you could inspect it, but it's the same with canvas.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM