2011-02-05 7 views
0

이 문제는 항상 발생하고 일관성이없는 것으로 나타났습니다.jquery .text validation fail

jQuery는 실제 단어를 비교하려고 시도하지만 실패하기 때문에이 문제는 jquery .text 비교가 작동하지 않는 원인이됩니다.

예 : 'Second Title'은 브라우저에서 1 행의 단어로 표시되지만 HTML 소스를 볼 때 'Second'와 'Title'은 다른 행에 있습니다.

따라서 if($(this).text()=="Second Title")이 작동하지 않습니다.

그런 경우 html 소스에서 공백을 제거하는 좋은 방법은 무엇입니까? 그래서 .text 비교를 계속 사용할 수 있습니다.

샘플이 작동하지 않는 버전을 보여줍니다.

 <table border="0" cellpadding="0" cellspacing="1"> 

      <tr> 
      <td width="400" colspan="3" align="center"><span>First Title</span></td> 
      </tr> 

      <tr align="center"> 
      <td>1</td> 
      <td>2</td> 
      <td>3</td> 
      </tr> 

     <tr> 
      <td width="400" colspan="3" align="center"><span>Second 
       Title</span></td> 
      </tr> 

      <tr align="center"> 
      <td>4</td> 
      <td>5</td> 
      <td>6</td> 
      </tr> 

    </table> 




$(document).ready(function() { 

    replaceText(); 

}); 


function replaceText() 
{ 

    var first, second 
    first= "", second=""; 

    $("*").each(function() { 
     if($(this).children().length==0) 
     { 
      if($(this).text()=="First Title") 
      {     
       first+= jQuery.trim($(this).closest('tr').next('tr').find("td").eq(0).text()); 
      } 

      if($(this).text()=="Second Title") 
      {     
       second+= jQuery.trim($(this).closest('tr').next('tr').find("td").eq(0).text());     
      }          
     } 
    });  


alert(first); 
alert(second); //fail 

} 

답변

1

당신이 공백 (예를 들어, 3 개 공간)의 반복에 의존하지 않는 경우 공백으로 연속하는 모든 공백을 대체 할 수있다.

function shrinkWhitespace(t) { 
    return t.replace(/\s+/g, ' '); 
} 

>> shrinkWhitespace('Second \n\tTitle') == 'Second Title' 
true