|
-
Mar 13th, 2006, 03:52 PM
#1
Thread Starter
Fanatic Member
[RESOLVED] need help for "looping"
Hi, I want to use a "for loop" to shorten the coding for the "if....." part only, but I am not sure how to...
//I am tring this but..
for (var m=1;m<4;m++)
{
if(horse[m].style.posLeft>800)
{
alert(m+"..horse won the race")
}
}
could anyone help me?
Thanks
PHP Code:
<script>
var sstop=setInterval("run()",50)
function run()
{
document.getElementById("horse1");
document.getElementById("horse2");
document.getElementById("horse3");
document.getElementById("horse4");
horse1.style.posLeft=horse1.style.posLeft+(Math.random()*10)+1;
horse2.style.posLeft=horse2.style.posLeft+(Math.random()*10)+1;
horse3.style.posLeft=horse3.style.posLeft+(Math.random()*10)+1;
horse4.style.posLeft=horse4.style.posLeft+(Math.random()*10)+1;
if(horse1.style.posLeft>800)
{
alert("horse1 won the race")
horse1.style.posLeft=10;
horse1.style.posLeft=horse1.style.posLeft+(Math.random()*0)+1;
//....................
//...............
}
}
</script>
<img src="horse.gif" id=horse1 style="position:absolute;top:200;left:10;">
<img src="horse.gif" id=horse2 style="position:absolute;top:230;left:10;">
<img src="horse.gif" id=horse3 style="position:absolute;top:260;left:10;">
<img src="horse.gif" id=horse4 style="position:absolute;top:290;left:10;">
-
Mar 13th, 2006, 05:18 PM
#2
Re: need help for "looping"
Why not use while?
Code:
var i = 1;
while (i < 5) {
var horse = document.getElementById('horse' + i);
horse.style.posLeft = horse.style.posLeft + (Math.random()*10) + 1;
if(horse.style.posLeft >= 800) {
alert('Horse ' + i + ' won the race!');
var j = 1;
while (j < 5) { document.getElementById('horse' + j).style.posLeft = 10; j++; }
}
i++;
}
Remember to test with something else than IE, too. There are some differences between browsers.
-
Mar 13th, 2006, 05:27 PM
#3
Thread Starter
Fanatic Member
Re: need help for "looping"
Thanks Merii,
You are a hero...it work perfect...
I like Javascript...
-
Mar 13th, 2006, 05:31 PM
#4
Re: [RESOLVED] need help for "looping"
Oh, just noticed:
Code:
horse.style.posLeft = horse.style.posLeft +
could be:
Code:
horse.style.posLeft +=
No need to repeat that twice
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|