-2

I have this series of nested loops that controls the layout of a series of tabs within a document.

var k=0;
while(k<document.getElementsByTagName("h7").length){
  for(i=0;i<5;i++){
    document.getElementsByTagName("h2")[k].style.left=i*154+"px";
    document.getElementsByTagName("h7")[k].style.left=i*154+"px";
    if(i==0){
        document.getElementsByTagName("h2")[k].style.left="42px";
        document.getElementsByTagName("h7")[k].style.left="42px";
    }
    k++;
  }
}

It works in the browser console with an error saying that document.getElementsByTagName("h2")[k].style.left=i*154+"px"; is undefined. I assume that there's something wrong with my k variable scope. Can anyone help me? I've tried all kinds of things, including passing the parameter k instead of using a variable but nothing seems to resolve the issue.

Here's a fiddle http://jsfiddle.net/zbpzu/

Here's the sample HTML

<h2>Header 2-1</h2>
<h7>header 7-1</h7>

<h2>Header 2-2</h2>
<h7>header 7-2</h7>

<h2>Header 2-3</h2>
<h7>header 7-3</h7>

<h2>Header 2-4</h2>
<h7>header 7-4</h7>

<h2>Header 2-5</h2>
<h7>header 7-5</h7>

<h2>Header 2-6</h2>
<h7>header 7-6</h7>

<h2>Header 2-7</h2>
<h7>header 7-7</h7>

<h2>Header 2-8</h2>
<h7>header 7-8</h7>

<h2>Header 2-9</h2>
<h7>header 7-9</h7>

<h2>Header 2-10</h2>
<h7>header 7-10</h7>

<h2>Header 2-11</h2>
<h7>header 7-11</h7>

<h2>Header 2-12</h2>
<h7>header 7-12</h7>

<h2>Header 2-13</h2>
<h7>header 7-13</h7>

Thank you!

4

2 回答 2

0

感谢 Crazy Train 指出问题......这是解决方法!

for(k=0;k<document.getElementsByTagName("h7").length;){
for(var i=0;i<5;i++){
  if(k<document.getElementsByTagName("h7").length){
    document.getElementsByTagName("h2")[k].style.left=i*154+"px";
    document.getElementsByTagName("h7")[k].style.left=i*154+"px";
    if(i===0){
        document.getElementsByTagName("h2")[k].style.left="42px";
        document.getElementsByTagName("h7")[k].style.left="42px";
    }
    k++;
   }
}
}

我需要额外的 if 语句来确保内循环不会比外循环长。

于 2013-07-31T13:28:55.390 回答
0

我建议使用 for 循环 for ktoo likei

var h7length=document.getElementsByTagName("h7").length;
for(k=0;k<h7length;k++){
  for(i=0;i<5;i++){
    if(i==0){
        document.getElementsByTagName("h2")[k].style.left="42px";
        document.getElementsByTagName("h7")[k].style.left="42px";
    }
    else
    {
    document.getElementsByTagName("h2")[k].style.left=i*154+"px";
    document.getElementsByTagName("h7")[k].style.left=i*154+"px";
    }
  }
}
于 2013-07-30T16:51:48.403 回答