简体   繁体   中英

errors in external javascript file

I have a javascript that works when placed in the head of my html. It dynamically changes a background image in a 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>

I would like to use it as an external .js file, but when I save the script as dynamicbg1.js and call it like this: <script src="http://someurl.com/js/dynamicbg1.js"></script> I get errors, and the images won't load. this is is the error I get: "SyntaxError: missing } after function body" but when I append a } like this in 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] + ')';
    }

I get the same error. Can anyone help me get the script to work as an external .js file?

When you append the } you are closing the block you opened with if (document.images) { .

That still leaves the function open.

You need another } .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM