Javascript for循环应循环两次,为什么只循环一次?

时间:2011-05-26 06:59:58

标签: javascript html css debugging

我有一个最奇怪的问题,我有一个循环,应该循环两次(它应该循环与HTML块中的textarea元素相同的数量,所以2)而不是它只循环一次?

为什么你认为这种情况正在发生?

  // This is the test HTML that should make the loop further below loop twice
  <div class="inputPanel">  
     <div class="a"> 
     <p class="label">Staff Link</p> 
     <textarea class="updatable~p"> abcdef </textarea>    
     <p> blah blah </p>
     <div class="b"> defgh </div>
     <p class="label">Staff Info</p>
     <textarea class="updatable~p"> erdeffde </textarea>
     <div class="footer"> end </div>
  </div>


function convertToDisplayHTML( str )
{
    try
    {
                       // Algorithm:
        // get all code from iframe 
        // extract all textarea elements
        // if textarea[i].class.match( "updable" )
        /* {
              var eleType = textarea[i].class.split("~");
              eleType     = eleType[ eleType.length-1 ];
              change elements type to eleType
              change elements value to textareas value
           }

           delete all elements that are <p>'s & have the class="label"

           return string
        */

        var textareas = document.getElementById("inputPanel").getElementsByTagName("textarea");
        var labels    = getElementsByClassName( "label", document.getElementById("inputPanel") );
        alert(textareas.length);  // says "2"

                       // THIS IS THE LOOP: it should loop 2 times not 1
        for ( var i=0; i<textareas.length; i++ )
        {
            alert("Loop 1 " + textareas[i].className);
            if ( textareas[i].className.match( "updatable" ) )
            {
                var className = "";
                var eleType   = textareas[i].className.split( "~" );
                eleType       = eleType[ eleType.length-1 ];

                if ( labels.length > 0 )
                {
                    var className = "updater~"+labels[0].innerHTML;
                    labels[0].parentNode.removeChild( labels[0] );
                    labels.shift();
                }

                var newObj  = changeObjectType( textareas[i], eleType, className );
            }
            alert("A");
        }

        return document.getElementById("inputPanel").innerHTML;
    }
    catch (ex)
    {
        alert("In convertToDisplayHTML(): "+ex);
        return "FAILED";
    }
}

1 个答案:

答案 0 :(得分:1)

labels没有名为shift的函数。

这就是我收到错误的地方。评论出来(以及对你未定义的changeObjectType的调用)解决了我的问题。