jquery
2013-02-24 100 views 0 likes 
0

我想應用jQuery text()方法以轉義包含<或> 這樣的字符的html內容,該內容「預先」添加到div塊,即就是爲什麼我需要<和>進行轉義jQuery如何將text()應用於變量

我無法弄清楚如何在這個例子中這樣做:http://jsfiddle.net/n28uf/2/

<div class="container"></div> 

jQuery(function(){ 
    var content = '<hello world>'; 
    jQuery('.container').prepend(content); 
    // Where should I apply the .text() method? 
}); 

我嘗試這樣做:

jQuery('.container').prepend(jQuery.text(content)); 

但我收到此錯誤信息:

Uncaught RangeError: Maximum call stack size exceeded 

http://jsfiddle.net/n28uf/2/的我應該穿什麼改變的代碼有它正常工作的任何想法?

感謝

回答

2

大約在前面加上一個包裝的div,然後填充,使用什麼.text()

jQuery(function(){ 
    var content = '<hello world>'; 
    jQuery('.container').prepend('<div class="foo"></div>'); 
    jQuery('.foo').text(content); 
}); 

http://jsfiddle.net/AfW5k/

1
  1. 內容添加到使用text()逃脫它的臨時jQuery對象。
  2. 使用html()從臨時對象中檢索轉義的內容。
  3. 將轉義內容添加到容器中。

樣品的編號:

<div class="container"></div> 

<script type="text/javascript"> 
jQuery(function(){ 
    var content = '<hello world>'; 
    var escapedContent = jQuery('<div></div>').text(content).html(); 
    jQuery('.container').prepend(escapedContent); 
}); 
</script> 

這導致以下生成的HTML源代碼:

<div class="container">&lt;hello world&gt;</div> 

總之,使用text()逃脫的內容,並使用html()檢索它不失去了逃脫的角色。

相關問題