保留从$ .get jquery调用返回的文本的空格和格式

时间:2010-04-05 04:07:17

标签: formatting jquery

我的app中有一个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);
}

响应数据在我添加到我的div的新行中显示为ABC,而源页面div有 一个

ç

我应该补充一点,这个脚本是Google Chrome扩展程序的一部分,因此这是我测试过的唯一一个浏览器

2 个答案:

答案 0 :(得分:2)

尝试使用.html而不是.text:

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

答案 1 :(得分: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>";