外部javascript文件错误

errors in external javascript file

本文关键字:错误 文件 javascript 外部      更新时间:2023-09-26

我有一个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: missing} after function body"但是当我像这样在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) {打开的块。

函数仍然是开放的。

你需要另一个}