新的Image()应该添加.src?

时间:2012-09-20 08:50:12

标签: javascript

关于新Image()的问题

以下代码来自'JavaScript by Example Second Edition',我认为

planet[0] = "images/Venus.jpg" 

错了,应该是

planet[0].src = "images/Venus.jpg" 

并替换

document.images["planet_pic"].src = planet[i]; 

document.images["planet_pic"].src = planet[i].src;

是不是?

<!DOCTYPE html>
<html>
<head>
    <title>Slide Show</title>
    <script type="text/javascript">
        var i = 0;
        var timeout;
        function preLoadImages() {
            if (document.images) {
                planet = new Array(); // global variable
                planet[0] = new Image();
                planet[0] = "images/Venus.jpg";
                planet[1] = new Image();
                planet[1] = "images/Neptune.jpg";
                planet[2] = new Image();
                planet[2] = "images/Earth.jpg";
                planet[3] = new Image();
                planet[3] = "images/Mars.jpg";
                planet[4] = new Image();
                planet[4] = "images/Jupiter.jpg";
            }
            else {
                alert("There are no images to preload");
            }
        }
        function startSlideShow() {
            if (i < planet.length) {
                document.images["planet_pic"].src = planet[i];
                i++;
            }
            else {
                i = 0;
                document.images["planet_pic"].src = planet[i];
            }
            timeout = setTimeout('startSlideShow()', 1500);
        }
        function stopSlideShow() {
            clearTimeout(timeout);
        }
    </script>
</head>
<body bgcolor="black" onload="preLoadImages()">
    <img name="planet_pic" src="/images/Jupiter.jpg" height="348"
        width="545px" />
    <form>
        <br />
        <br />
        <input type="button" value="Start Show"
            onclick="return startSlideShow();" />
        <input type="button" value="Stop Show"
            onclick="return stopSlideShow();" />
    </form>
</body>
</html>

1 个答案:

答案 0 :(得分:1)

是的,它应该是,

planet[0] = new Image();
planet[0].src = "images/Venus.jpg";