2011-09-23 8 views
0

특정 클래스의 모든 HTML 요소를 textarea 요소의 &으로 변환하는 JQuery 코드가 있습니다.

문제점 : JQuery (.addClass())를 사용하여 요소 클래스를 "updatable"에서 "updatable P"로 변경합니다. 그러나 "$ (". updatable "). each() 함수를 사용하여"업데이트 가능 "클래스를 가진 모든 요소를 ​​검색 할 때 3을 찾을 때 요소를 찾지 않습니다.

이 일을하도록 내가 잘못하고있는 것은 무엇입니까? 그것은 요소 클래스를 변경 한 후 나는 그 클래스를 (JQuery를 사용하여) 해당 요소를 식별/찾을 수 없습니다. 당신은 (according to the spec가) 완전히 모든 컨텐츠를 제거하고 새로운 콘텐츠로 대체 replaceWith를 사용하는

<html> 
<head> 

    <script type="text/javascript" src="jquery-1.6.4.js"></script> 
    <script type="text/javascript"> 
    <!-- 
     var STATE = 1; 

     function Toggle() 
     { 
      if (STATE==1) { convertToUpdatable(); STATE = 0; } 
      else   { convertToStatic(); STATE = 1; } 
     } 

     function getTitleName(ele) 
     { 
      try  { return ele.className.split(" ")[1]; } 
      catch (ex) { return "undefined"; } 
     } 

     function convertToUpdatable() 
     { 
      // Post: Convert all HTML elements (with the class 'updatable') to textarea HTML elements 
      //  and store their HTML element type in the class attribute 
      // EG: Before: <p class="updatable Paragraph1"/> Hello this is some text 1 </p> 
      //  After : <p class='updatableElementTitle'>Paragraph1</p><textarea class="updatable Paragraph1 p"/> Hello this is some text 1 </textarea> 

      $(".updatable").each(function() 
       { 
        var title = getTitleName(this); 
        $(this).replaceWith("<p class='updatableElementTitle'>"+title+"</p><textarea>"+$(this).text() +"</textarea>"); 
        $(this).addClass(this.nodeName); 
        alert(this.className); 
       }); 
     } 

     function convertToStatic() 
     { 
      // Post: Find all HTML elements (with the class 'updatable'), check to see if they are part of another class aswell 
      //  (which will be their original HTML element type) & convert the element back to that original HTML element type 

      // PROBLEM OCCURS HERE: after I have changed an elements className in the convertToUpdatable() I can no 
      //      longer find any HTML elements that have the className updatable using $(".updatable").each() 
      $(".updatable").each(function() 
       { 
        alert("Loop"); 
        // Determine elements original HTML(node) type 
        try 
        { 
         var type = this.className.split(" "); 
         type  = (type[ type.length-1 ]).toLowerCase(); 
         alert(type); 
        } 
        catch (ex) { alert("Updatable element had no type defined in class attribute"); return; } 

        // Convert element back to original HTML type 
        $(this).replaceWith(type +$(this).text() + type); 

        // Remove elements type from its className (remove " P" from "updatable Paragraph1 P") 
        $(this).removeClass(type); 
        alert(this.className); 
       }); 

      // Delete all elements with the class 'updatableElementTitle' 
      $(".updatableElementTitle").remove(); 
     } 

    --> 
    </script> 
</head> 
<body> 

    <p class="updatable Paragraph1"/> Hello this is some text 1 </p> 
    <b class="updatable Paragraph2"/> Hello this is some text 2 </b> 
    <i class="updatable Paragraph3"/> Hello this is some text 3 </i> 

    <input id="MyButton" type="button" value="Click me!" onclick="Toggle();" /> 

</body> 
</html> 

답변

1

.replaceWith()은 기존 요소를 파괴합니다. 따라서 루프에서 replaceWith()을 수행 한 후에는 더 이상 this을 사용할 수 없습니다. DOM 요소는 더 이상 문서에있는 요소가 아니기 때문에 더 이상 사용할 수 없습니다 (이전에 제거 된 요소이므로 사용자 함수가 가비지 수집됩니다. 종료).

새 태그에 HTML을 지정 했으므로 replaceWith()에 전달하는 HTML에 새 클래스 이름을 넣는 것이 좋습니다. 또한 className을 확인해야한다는 경고는 새 DOM 요소가 아니라 이전 DOM 요소를 확인하는 것입니다. this은 이전 DOM 이름을 가리키며 사용자가 바꾼 DOM 이름이 아닙니다.

이를 변경하여 그렇게 할 수있는이에

 $(".updatable").each(function() 
      { 
       var title = getTitleName(this); 
       $(this).replaceWith("<p class='updatableElementTitle'>"+title+"</p><textarea>"+$(this).text() +"</textarea>"); 
       $(this).addClass(this.nodeName); 
       alert(this.className); 
      }); 
    } 

을 : 당신이 클래스로 노드 명을 추가하는 이유를 이해하지 않지만

 $(".updatable").each(function() 
      { 
       var title = getTitleName(this); 
       $(this).replaceWith("<p class='updatableElementTitle " + this.nodeName + "'>" + title + "</p><textarea>"+$(this).text() +"</textarea>"); 
      }); 
    } 

를?

+0

+1 : 당신은이 답변으로 나를 때렸다. – nnnnnn

1

. 내용을 바꾼 후에는 updatable 클래스가있는 노드가 더 이상 없으므로 다시 찾을 수 없습니다.

$(this).addClass(this.nodeName);$(this).addClass('updatable');으로 바꾸어보세요.

관련 문제