开发者

Javascript will not load the pictures

I want to load these banner.png files to the screen but all it prints out is 开发者_运维知识库the actual text from the banner array?

function randImg(){
var banner = new Array();

banner[0] = 'banner1.png';
banner[1] = 'banner2.png';
banner[2] = 'banner3.png';
maxImg = banner.length;
randNum = Math.floor(Math.random()*maxImg);
return banner[randNum];
}

any thoughts? I think I need to some how add a src but I am not sure how.


Might be too obvious, but...

function randImg(){
    var banner = new Array();

    banner[0] = 'banner1.png';
    banner[1] = 'banner2.png';
    banner[2] = 'banner3.png';
    maxImg = banner.length;
    randNum = Math.floor(Math.random()*maxImg);
    return '<img src="' + banner[randNum] + '" />';
}

Demo: http://jsfiddle.net/AlienWebguy/u7yfq/


My pure javascript DOM manipulation is a little fuzzy (usually use jquery) but something like this should do the trick:

<div id="images"></div>    

<script type="text/javascript">
function randImg(){
       var banner = new Array();

       banner[0] = 'banner1.png';
       banner[1] = 'banner2.png';
       banner[2] = 'banner3.png';
       maxImg = banner.length;
       randNum = Math.floor(Math.random()*maxImg);

       var container = document.getElementById('images');

       var img = document.createElement('img');
       img.setAttribute('src',banner[randNum]);

       container.appendChild(img);
    }
</script>


The instruction that loads the image should be like this.

Where imgElement is an IMG element.

imgElement.src = randImg();

If you don’t know how to get an IMG element. Give the IMG element an ID attribute and load this like this.

For an IMG element as <img id="myImage" src="" /> Then:

var imgElement = document.getElementById("myImage");
imgElement.src = randImg();

Note.- my answer gives instruction on how to change the source of an IMG element that exists in the DOM (It is recommended to do so). You should NEVER document.write() an element, Neither on demand or when page is loading. That practice has been deprecated and many browsers would delete the whole page contents if you do so.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜