简体   繁体   中英

javascript display multiple Highcharts using single function

I am trying to display multiple highcharts on the same webpage in different containers. I know that I can just copy and paste a standard highcharts function a bunch of time to render many graphs to a page in different containers, but since the number of highcharts I want to display is going to depend on a value that is extracted from a database (in the example below the number of charts will be equal to @value) I ideally want to write just one highcharts function, and loop over it many times, where in each iteration I would like to set the chart options to be something different. I've tried various permutations the following code:

for (i = 0; i <= <% @value %>; i ++){
    $(function (i) {
       graphTitleArray = <% @markers.split(',') %>
       graphTitle = graphTitleArray[i]
       graphData = <% @array[i].to_json %>
       switch(i){
          case 0:
             containerNum =  'container0'
          case 1:
             containerNum = 'container1'

          ...
       }
       $(containterNum).highcharts({
          title: {
             text: graphTitle
          }
          series: [{
                name: 'something',
                data : graphData
            }]
         //more options here
       })
    }
}

After trying this type of strategy multiple times, I can't get the graphs to render or get the function to recognize the correct value of 'i'. Does anyone know a better way to do this? Thanks!

I think you are selecting the containers wrong. I've corrected it below (assuming values such as 'container0' are the id of the container), including getting rid of the non-needed case statement.

for (i = 0; i <= <% @value %>; i ++){
   graphTitleArray = <% @markers.split(',') %>
   graphTitle = graphTitleArray[i]
   graphData = <% @array[i].to_json %>

   $('#container'+i).highcharts({
      title: {
         text: graphTitle
      }
      series: [{
            name: 'something',
            data : graphData
        }]
     //more options here
   })
}

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