2016-04-09 56 views
1

任何人都可以幫助解決此錯誤。JavaScript未定義對象,即使通過F12檢查時也顯示數據

下面是代碼:

$(document).ready(function(){ 

var certifications = { 
    nextCert : 0, 
    data : [ 
    { 
     "imgSrc" : "http://res.cloudinary.com/sharek/image/upload/v1460011761/UC-PJNHKQ02_r1gjmj.jpg" 
    }, 
    { 
    "imgSrc" : "http://res.cloudinary.com/sharek/image/upload/v1460011761/UC-KE5C95GA_aid30q.jpg" 
    } 
    ], 
    getNextCert : function(){ 
    if(this.nextCert === this.data.length){ 
     this.nextCert = 0; 
    } 
    else{ 
     this.nextCert += 1; 
    } 
    return this.nextCert; 
    }, 
    getCurrentCert : function() { 
    return this.nextCert; 
    }, 
    getImgCert : function() { 
     return this.data[this.getNextCert()]; 
    } 

};//certification object 

var certContainer = $('#cert-container').html 

var templateItem = $(certContainer); 
templateItem.find('.img-responsive').attr('src',certifications.getImgCert()['imgSrc']); 

$('#nextBtn').click(function(){ 
    console.log(certifications.getImgCert()['imgSrc']); 
    templateItem.find('.img-responsive').attr('src',certifications.getImgCert()['imgSrc']); 

    }); 

});//document.ready 

而這裏所有的主頁我的工作:

http://codepen.io/abomaged/pen/JXMXzV

非常感謝

+1

。移動的document.ready – mplungjan

+0

喜mplungjan外'VAR certifications',我想你說的一點用也沒有,我剛纔忘了說,有一個認證變量中的數據,並且該腳本正在工作,即使它僅在控制檯中顯示錯誤。謝謝 –

+0

是的,你還需要測試this.nextCert後增加回答 – mplungjan

回答

1

這是因爲你的getNextCert函數是re轉向超出認證數組界限的索引。當nextCert爲1時,檢查數組是否越界,所以你的代碼會將nextCert遞增爲2並返回未定義的data[2]。你需要改變你的getNextCert功能:

getNextCert : function(){ 
    this.nextCert += 1; 
    if(this.nextCert === this.data.length){ 
     this.nextCert = 0; 
    } 
    return this.nextCert; 
    }, 
+0

感謝Vadim,問題解決了。我感謝您的幫助... –

相關問題