How to randomly change inline images on page load and each refresh, using jquery?

断了今生、忘了曾经 提交于 2019-12-12 15:01:50

问题


What is the best lightweight way to randomly show inline images from a folder on each refresh or on load a page ? using jQuery.

like jQuery version of this http://javascript.internet.com/miscellaneous/random-image.html

Update: 24 April

This is exactly what i want i just need unobtrusive jQuery version of this

<div class=”me-box”>

<script language=”JavaScript”>
function banner() { } ; b = new banner() ; n = 0
b[n++]= “<img name=randimg src=’images/me.jpg’ >”
b[n++]= “<img name=randimg src=’images/me2.jpg’ >”
b[n++]= “<img name=randimg src=’images/me4.jpg’ >”
b[n++]= “<img name=randimg src=’images/me5.jpg’ >”
b[n++]= “<img name=randimg src=’images/me6.jpg’ >”
b[n++]= “<img name=randimg src=’images/me3.jpg’ >”
i=Math.floor(Math.random() * n) ;
document.write( b[i] )
</script>

</div>

回答1:


I found solution here

http://www.robwalshonline.com/posts/jquery-plugin-random-image-on-page-load/




回答2:


jQuery by itself can not read a folder's contents. Unless you do some magic like name the files for example 1.jpg, 2.jpg and include an upperbound in the script.

You should probably use a server side language to read the folder and pass some JSON to your JavaScript. Then just loop the JSON and display.

$.getJSON('get/files', function(data) {

    $.each(data, function(image) {
        $('#my-div ul').append('<li><img src="' + image + '" alt="" />');
    });

});



回答3:


I guess it would depend on how many pics you are talking about and if they will change frequently. Let's say there aren't many and the list will stay pretty much the same. You could through their file names into an array and then randomly generate a number based on the length of the array's index.

$(document).ready(function() {
    var rndNumber;
    var displayPictures = new Array();
    displayPictures[0...n] = 'filename.jpg';

    rndNumber = (Math.floor(Math.random()*displayPictures.length));

    $('#picture_tag_id_name').attr('src', 'images/'+displayPictures[rndNumber]);

});

When I tried this on a site, I used inline PHP to loop through the contents of the image folder and 'echo' out the lines that populate the array with the strings of all the image paths.

May not be the best way but it is a way.



来源:https://stackoverflow.com/questions/2696321/how-to-randomly-change-inline-images-on-page-load-and-each-refresh-using-jquery

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!