2017-09-18 3 views
0

単一のページアプリケーションを作成しようとしていますが、ナビゲーション項目をクリックしている間にjquery loadを使用してコンテンツを置き換えています。jQueryを使用してHTMLコンテンツを読み込んでJavaScriptを実行する方法は?

コンテンツを初期化するためにjavascriptを実行する必要があるページがあります。 (私の例では、chart.jsで作成された折れ線グラフを初期化したい)

他の人から聞いた前の質問では、loadのコールバック関数にコードを配置すると書かれていますが、私のために働く、または私は何か間違っている。 jQuery .load() html content and execute script

コード:

$(document).ready(function() { 


var hash = window.location.hash.substr(1); 
var href = $('#nav li a').each(function() { 
    var href = $(this).attr('href'); 
    if (hash == href.substr(0, href.length - 5)) { 
     var toLoad = hash + '.html #content'; 
     $('#content').load(toLoad) 
    } 
}); 

$('#nav li a').click(function() { 

    var toLoad = $(this).attr('href') + ' #content'; 
    $('#content').hide(); 
    loadContent(); 
    window.location.hash = $(this).attr('href').substr(0, $(this).attr('href').length - 5); 

    function loadContent() { 
     $('#content').load(toLoad, '', showNewContent()) 

    } 

    function showNewContent() { 

     $('#content').show('fast',loadChartData); 

    } //end of show content 

    // My javascript to initialize my loaded content, in my case, I am 
    trying to initialize a chart.js line chart. 

    function loadChartData(){ 


     new Chart(document.getElementById("line-chart"), { 
      type: 'line', 
      data: { 
       labels: [1500, 1600, 1700, 1750, 1800, 1850, 1900, 1950, 1999, 2050], 
       datasets: [{ 
        data: [86, 114, 106, 106, 107, 111, 133, 221, 783, 2478], 
        label: "Africa", 
        borderColor: "#3e95cd", 
        fill: false 
       }, { 
        data: [282, 350, 411, 502, 635, 809, 947, 1402, 3700, 5267], 
        label: "Asia", 
        borderColor: "#8e5ea2", 
        fill: false 
       }, { 
        data: [168, 170, 178, 190, 203, 276, 408, 547, 675, 734], 
        label: "Europe", 
        borderColor: "#3cba9f", 
        fill: false 
       }, { 
        data: [40, 20, 10, 16, 24, 38, 74, 167, 508, 784], 
        label: "Latin America", 
        borderColor: "#e8c3b9", 
        fill: false 
       }, { 
        data: [6, 3, 2, 2, 7, 26, 82, 172, 312, 433], 
        label: "North America", 
        borderColor: "#c45850", 
        fill: false 
       }] 
      }, 
      options: { 
       title: { 
        display: true, 
        text: 'World population per region (in millions)' 
       } 
      } 
     }); 

    } 
    return false; 
}); 
}); 

私は何をすべき?

+0

コンソールにエラーやログはありますか? –

+0

私は1つが表示されません。 – user2386301

+0

イベントを関数内で定義するのは悪い習慣です。 '$(document).ready()'の外でも関数定義を取っておけば、いつでもどこでも呼び出すことができます。 –

答えて

0

ロード関数$(セレクタ).load(URL、データ、コールバック)は、コールバックを持つことができます。したがって、load関数に送られるコールバック内のchart.jsの初期化関数を呼び出します。初期化の前にDOMを配置する必要があります。

$('#content').load(toLoad, '', callback); 

function callback() { 
    // wait for DOM to initialize 
    // Initialize content using chart.js 
} 
関連する問題