CodingForums.com

CodingForums.com (http://www.codingforums.com/index.php)
-   JavaScript programming (http://www.codingforums.com/forumdisplay.php?f=2)
-   -   for loop help (http://www.codingforums.com/showthread.php?t=282274)

Md8^h2nx 11-15-2012 06:06 PM

for loop help
 
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.
Code:

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.

Code:

<!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==&#34;change" + i + "&#34;) {<br>x.className=&#34;change#&#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.

Code:

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


devnull69 11-15-2012 07: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??
Code:

// 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 07: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.


All times are GMT +1. The time now is 02:02 AM.

Powered by vBulletin®
Copyright ©2000 - 2013, Jelsoft Enterprises Ltd.