2010-04-05 29 views
1

我的應用程序中有一個jquery $ .get()調用請求整個網頁。在回調函數中,我訪問返回頁面中的div,獲取其數據並將其顯示在我的頁面上。

問題是我從div得到的文本不保留源格式。如果請求頁面中的div有說出有序列表,那麼當我得到該文本並顯示在我的頁面上時,它會顯示爲帶有內聯項目的段落,而不是顯示爲列表。

我不知道問題是$ .get()是獲取數據還是顯示數據。

//get the page 
     $.get($(this).attr('href'), function(data){ 
       callbackFunc(data,myLink); 
      }, 
      "html"); 

    function callbackFunc(responseText, customData){ 

     //response has bg color of #DFDFDF 
     var td = $("td[bgcolor='#DFDFDF']", responseText); 

     //text to show is in div of that td 
     var forumText = $('div', td).text(); 

     //append new row with request data below the current row in my table 
     var currentRow = $(customData).parent('td').parent('tr'); 
     var toAppend = "<tr><td class='myTd' colspan='3'>" + forumText + "</td></tr>"; 

     $(currentRow).after(toAppend); 
} 

響應數據顯示像ABC新行我添加到我的div而源頁面的div有
一個

下,在

我要補充一點,這個腳本是部分Google Chrome瀏覽器的擴展程序,因此這是我測試的唯一瀏覽器

回答

2

嘗試使用.html代替.text:

var forumText = $('div', td).html(); 
0

我偶然發現了這個線程,因爲我也需要保存格式。但是,使用.html()而不是.text()不是一種選擇,因爲有人可能以這種方式注入JavaScript攻擊。我在this stackoverflow thread上找到了我正在尋找的解決方案。

因此,例如,改變你的代碼下面幾行保留空白,同時仍然使用的.text()使用白色空間CSS樣式:

var toAppend = '<tr><td class="myTd" colspan="3" style="white-space: pre-line;">' 
+ forumText + "</td></tr>";