2011-02-05 7 views
0

この問題は常に起こり、一貫性がないことがわかりました。jqueryの.text検証に失敗しました

この問題は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 
関連する問題