簡體   English   中英

外部javascript文件中的錯誤

[英]errors in external javascript file

我有一個 javascript,當放在我的 html 的頭部時它可以工作。 它動態更改 div 'bg' 中的背景圖像。

<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>我收到錯誤,圖像無法加載。 這是我得到的錯誤:“SyntaxError:在函數體之后缺少}”但是當我在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 文件工作嗎?

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

這仍然使函數保持打開狀態。

你需要另一個}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM