开发者

Why does changing the name of my function break my JavaScript?

I have the following which works perfectly

$(function() {

    // Create the chart
    chart = new Highcharts.StockChart({
        ...
    });
});

However when I make the following modification

c开发者_C百科reateCharts();
function createCharts() {

    // Create the chart
    chart = new Highcharts.StockChart({
        ...
    });
}

I get the following error message

Message: 'Highcharts' is undefined

Nothing else has changed why does the above break my script?


In your first example, the function is called when the document is ready (ie, after the HighCharts script has been loaded). In your second example, the HighCharts script is probably defined after the script you're running so you need to either wait for document ready:

$(createCharts); // <- pass createCharts to $()/jQuery.ready()
function createCharts() {

    // Create the chart
    chart = new Highcharts.StockChart({
        ...
    });
}

... or change the order of your scripts:

<head>
  <!-- libraries first -->
  <script src="jquery.js"></script>
  <script src="highcharts.js"></script>

  <!-- your script last -->
  <script src="myscript.js"></script>
</head>


On the first example, the function runs AFTER the file containing the Highcharts definition was loaded. On the second, it executes as soon as it find the function definition, probably before the Highcharts file was loaded.


Probably because the Highcharts library hasn't loaded yet with the second one. Are you running this code before you load the highcharts js file?


$() is a special function that waits for the dom to be ready.

http://api.jquery.com/ready/

I'm guessing that Highcharts hasn't been created by the time createCharts is called, but is created before the DOM is ready.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜