How can I show a series of random images in a WordPress text widget using HTML/Javascript?
I'm using WordPress 3.0.5 on Dreamhost, trying to create a text widget in the sidebar that will show a random set of nine (9) client logos. There are a total of 12 logos, located in the /wp-content/clients folder, named logo1.jpg thru logo12.jpg.
The idea is to choose the first image randomly, then get the next eight images in sequential order to avoid duplicates.
UPDATE
Got it working, thanks for the tips everyone!
Here is the final, working version:
<div id="client-logos"></div>
<script type="text/javascript">
TotalLogos = 12;
FirstPart = '<img src="/wp-content/clients/logo';
LastPart = '.jpg" height="50" width="110" />';
var r = Math.ceil(Math.random() * TotalLogos);
var content = document.getElementById('client-logos').innerHTML;
document.getElementById('client-logos').inne开发者_开发知识库rHTML = FirstPart + r + LastPart;
var t=0;
for (t=0;t<8;t++)
{
if (r == TotalLogos) { r=0; }
r++;
var content = document.getElementById('client-logos').innerHTML;
document.getElementById('client-logos').innerHTML = content + FirstPart + r + LastPart;
}
</script>
document.write() runs before the page finishes loading.. you should use something else..
first of all, you should get object of your div container by id:
your html:
<div id="containerid"></div>
<script>
var elem = document.getElementById('containerid');
elem.innerHTML= "FirstPart + r + LastPart";
</script>
Just change t=8
to t<8
and it works (for me). The second expression in a for
loop means: "Execute the foor loop as long as this is true". Your code has to be executed as long as t < 8
; when t == 8
, it should stop.
Working example: http://jsfiddle.net/m7m7C/
精彩评论