...

View Full Version : for loop help



Md8^h2nx
11-15-2012, 07:06 PM
I'm working on a random project that takes a lot of code so I'm trying to use javascript to make it easier.

This is what I want to do.


else if(x.className=="change0") {
x.className="change1";
}
else if(x.className=="change1") {
x.className="change2";
}
else if(x.className=="change2") {
x.className="change3";
}

|
v
|
v
|
v

else if(x.className=="change358") {
x.className="change359";
}


I did a for loop for this.



<!DOCTYPE html>
<html>
<body onload="myFunction()">

<p id="demo"></p>

<script>
function myFunction()
{
var x="";
for (var i=0;i<359;i++)
{
x=x + "else if(x.className==&#38;#34;change" + i + "&#38;#34;) {<br>x.className=&#38;#34;change#&#38;#34;;<br>}<br>";
}
document.getElementById("demo").innerHTML=x;
}
</script>

</body>
</html>


I can't get the first number to start at 0 while the other number starts at 1.



else if(x.className=="change0") {
x.className="change1";
}

devnull69
11-15-2012, 08:28 PM
Oh my, what a construct. Ever heard of variables holding numbers and string concatenation?

The only thing you want to do is to count +1 for the class name of a certain DOM element? Which DOM element is "x" referring to??


// get your element
var x = document.getElementById('yourelement');
// extract the number from the className
var current = Number(x.className.match(/(\d+)/)[1]);
// replace this number with +1 number
if(current<=358) x.className = x.className.replace(/\d+/, current+1);

Old Pedant
11-15-2012, 08:28 PM
That code just makes no sense at all.

As written, you will be simply dumping what LOOKS like JavaScript AS TEXT into the contents of your <div id="demo">.

Total nonsense.



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum