简体   繁体   中英

Multiple usage of Javascript function

I got some code in JS which i use in my php script.( based on chartjs)

$licznik=0;
    foreach ($all as $key => $row) {
                                      $imiona[$licznik]=$row['imie'];
                                      $nazwiska[$licznik]=$row['nazwisko'];
                                      $tak[$licznik]=$row['tak'];
                                      $nie[$licznik]=$row['nie'];
                                      $licznik++;
                                    }


    $wynik.='<div>
      <canvas id="'.$team.'">
      </canvas>
      </div>
      <br><hr>';

   $wynik.='<script>

  var barChartData = {
    labels : ["'.wypiszimiona($imiona,$nazwiska,$licznik).'], //radni
    datasets : [
      { //głosy na nie
        fillColor : "#BA0606",
      strokeColor : "#FF0808",
        highlightFill: "rgba(220,220,220,0.75)",
        highlightStroke: "rgba(220,220,220,1)",
        data : ['.wypisznie($nie,$licznik).']
      },
      { //głosy na tak
        fillColor : "#23BA06",
        strokeColor : "#30F70A",
        highlightFill : "rgba(151,187,205,0.75)",
        highlightStroke : "rgba(151,187,205,1)",
        data : ['.wypisztak($tak,$licznik).']
      }
    ]
  };
  window.onload = function(){
    var ctx = document.getElementById("'.$team.'").getContext("2d");
    window.myBar = new Chart(ctx).StackedBar(barChartData, {
      responsive : true
    });

      };
  </script>';

It render only last canvas, the other one are not rendered ( but JS code is right (in source). I have no idea what's wrong. I'm not good in JS:(

Based on what little information you provide, I assume you are copying and pasting that js code with different php variables. Each time you do that, you are adding code that tells the client that

window.onload = function(){
    var ctx = document.getElementById("'.$team.'").getContext("2d");
    window.myBar = new Chart(ctx).StackedBar(barChartData, {
      responsive : true
    });

if you do this more than once, you are overwriting window.onload, and only the last rewrite will happen, meaning only the last canvas will be drawn to.

You need to close (and open in some of them) the JS strings with double quotes. There are a few lines that lack them:

...labels : ["'.wypiszimiona($imiona,$nazwiska,$licznik).'"]...
...data : ["'.wypisznie($nie,$licznik).'"]...
...data : ["'.wypisztak($tak,$licznik).'"]...

I might have missed some.

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