2010-02-10 225 views
2

我面臨解析HTML格式輸入文本的小問題。成功轉換開放和關閉標籤等,但我如何識別文本區域中的「下一行(輸入的文本)」?解析特殊字符並轉換爲HTML(轉義字符串)

請幫

<script type="text/javascript"> 

jQuery(function($) { 

    $('#submit').click(function() { 
    var htmlval = $('#textEntry').val(); 
    $('p.escape').text(htmlval); 
    $('p.escape').escapeHtml(); 
    }); 


}); 

(function($) { 


$.fn.escapeHtml = function() { 
    this.each(function() { 
     $(this).html(
      $(this).html() 
       .replace(/"/g,"&quot;") 
       .replace(/&/g,'&amp;') 
       .replace(/</g,'&lt;') 
       .replace(/>/g,'&gt;') 
       .replace(/'/g,'&apos;') 
     ); 
    }); 
    return $(this); 
} 

})(jQuery); 

</script> 

HTML如下:..

<p class="escape"></p> 
<br> 
<textarea name="text" id="textEntry"></textarea><input type="submit" id="submit" value="submit" /> 

回答

3

不要刻意逃避文本的客戶端,如果有人被人惡意他們只會手動提交它,並繞過花哨的JavaScript。在與數據庫進行交互之前,將文本服務器端轉義。

2

有一個JavaScript函數內置的權利!

$.fn.escapeHtml = function() { 
    return escape($(this)); 
} 

注:escape()不越獄使用HTML實體。它使用百分比編碼轉義,正如URI中所使用的。所以它與最初要求的不同。