2015-09-04 51 views
-3

我有一個JavaScript的作品,當放置在我的HTML的頭。 它動態更改div'bg'中的背景圖像。在外部JavaScript文件中的錯誤

<script type="text/javascript">window.onload = function() { 
    var header = document.getElementById('bg'); 
    var pictures = new Array('http://someurl.com/bgs/1.jpg', 
          'http://someurl.com/bgs/2.jpg', 
          'http://someurl.com/bgs/3.jpg', 
          'http://someurl.com/bgs/4.jpg', 
          'http://someurl.com/bgs/5.jpg'); 
    var numPics = pictures.length; 
    if (document.images) { 
     var chosenPic = Math.floor((Math.random() * numPics)); 
     header.style.backgroundImage = 'url(' + pictures[chosenPic] + ')';</script> 

我想用它作爲外部.js文件,但是當我保存腳本dynamicbg1.js並調用它像這樣: <script src="http://someurl.com/js/dynamicbg1.js"></script> 我得到的錯誤,並且圖像將不會加載。 這是我得到的錯誤: 「語法錯誤:在函數體內缺少}」 但是當我追加}像這樣在dynamicbg1.js:

window.onload = function() { 
    var header = document.getElementById('bg'); 
    var pictures = new Array('http://someurl.com/bgs/1.jpg', 
          'http://someurl.com/bgs/2.jpg', 
          'http://someurl.com/bgs/3.jpg', 
          'http://someurl.com/bgs/4.jpg', 
          'http://someurl.com/bgs/5.jpg'); 
    var numPics = pictures.length; 
    if (document.images) { 
     var chosenPic = Math.floor((Math.random() * numPics)); 
     header.style.backgroundImage = 'url(' + pictures[chosenPic] + ')'; 
    } 

我得到同樣的錯誤。 任何人都可以幫助我使腳本作爲外部.js文件工作嗎?

+0

試着更徹底,老兄! –

回答

3

當您附加}時,您將關閉您使用if (document.images) {打開的塊。

這仍然使功能打開。

您需要另一個}

+0

解決!謝謝! –

+0

這不應該是一個評論?我的意思是,它基本上是一個簡單的錯誤修正? – Icepickle