2016-03-06 16 views
0

我正在開發一個使用easeljs和jQuery創建圖像庫的小型項目,我對這兩個工具都很陌生,而且這個特殊問題讓我撓了撓頭。使用easeljs時未定義的init()函數

我的HTML是非常基本的,我只是想用的功能開始之前,我添加任何花裏胡哨:

<body onload="init();"> 
 
    <div style="margin-top:20px;" class="col-sm-8"> 
 
    <div class="embed-responsive embed-responsive-4by3"> 
 
     <canvas class="embed-responsive-item" id="slide-show" width="640" height="480"></canvas> 
 
    </div> 
 
    </div> 
 
</body>

如果我理解正確的話,以建立一個新的階段,基本上讓整個腳本工作,我需要在我的腳本開始時運行一個init()函數。

$(document).ready(function(){ 
 
    //declare global variables 
 
    var data; 
 
    var stage; 
 
    var canvas; 
 
    var images = []; 
 
    var bitmaps = []; 
 
    var imageCount = 0; 
 
    var slideshowInterval = 3000; 
 

 
    //connect to feed.json 
 
    $.ajax({ 
 
     url: 'json/feed.json', 
 
     datatype: 'json', 
 
     type: 'get', 
 
     cache: false, 
 
     success: function(data) { 
 
      data = data; 
 
     } 
 
    }); 
 

 
    function init(){ 
 

 
     canvas = document.getElementById('slide-show'); 
 
     stage = new createjs.Stage(canvas); 
 

 
     $(data.feed).each(function(index, value) { 
 
      //populate the images array with content from feed.json 
 
      images[index] = new Image(); 
 
      images[index].src = data.feed[index].source; 
 
      images[index].onload = imageLoaded; 
 
     }); 
 
    } 
 

 
    function imageLoaded(){ 
 
     // go through all images and create bitmaps for them. 
 
     imageCount++; 
 
     if(imageCount >= images.length - 1){ 
 
     createBitmaps(); 
 
     } 
 
    } 
 

 
    function createBitmaps(){ 
 
     // create the bitmaps and add them to an array 
 
     $(images).each(function(index, value){ 
 
     bitmaps[index] = new createjs.Bitmap(images[index]); 
 
     }); 
 
    } 
 

 
    function createSlider(){ 
 

 
     bitmaps.x = 0; 
 
     bitmaps.y = 0; 
 
     stage.addChild(bitmaps); 
 

 
     setTimeout(slideshowInterval, slideImage(index)); 
 
    } 
 

 
    function slideImage(index){ 
 

 
     // handle the animation of the slide effect and update dom with image details. 
 
     $('#biscuit-name').html(data.feed[index].name); 
 
     $('#biscuit-info').html(data.feed[index].text); 
 
    } 
 
});

也請注意,這肯定不算完,有些功能是成功的一半。我只是想做一些調試,因爲我在處理事情時遇到了麻煩,並且在初始化函數似乎沒有按照預期發射的情況下觸發了第一步。

回答

0

主要問題是<body onload="someFunction()">會在全局範圍內查找someFunction,即執行window.someFunction()

現在,你init()不在全球範圍內。它只存在於$(document).ready(function(){ ... })函數中。

所以,一個解決辦法是到init功能添加到全球範圍內,像這樣:

$(document).ready(function() { 
    // ... all your current definitions 
    window.init = init; 
}); 

注重這裏是init將只能定義和$(document).ready之後添加到window事實jQuery事件被觸發。但它不應該是一個問題,因爲$(document).ready通常早於[0123]比onload事件觸發,因此定義init,然後在<body onload="init()">中調用它。

[1] $(document).ready在加載了HTML文檔後觸發。 onload是在所有內容(包括圖像等)已被加載後觸發的內置DOM事件。

+0

感謝您的acdcjunior,這些事情之一,一旦有人顯示你哈哈! – pragmatic84

相關問題