用异步API调用替换HTML中的文本

时间:2015-02-27 08:39:15

标签: javascript google-chrome-extension content-script dom-traversal

我一次在一个页面5000个字符的所有HTML上调用异步函数,然后在我从API收到回复时想要替换5000个字符。但是,我无法替换现有的返回文本。

请注意,这是异步的,因此可以按任何顺序返回。返回的文本应该在适当的API函数返回时“弹出”。

var textbody = document.body.innerHTML;
var loops = textbody.length/5000;
var translatedHTML = '';

for (var i = 0; i < loops; i++) {
    (function (i) {
        var translatetext = document.body.innerHTML.substring(5000*i, (5000*i)+5000);
        //call an Async API to translatetext

       //callback for async API call
            {
                var translation = xmlhttp2.responseText;
                var refreshHTML = document.body.innerHTML;

                //WHAT AM I DOING HERE?! NEED TO REPLACE TEXT IN PLACE
                translatedHTML = refreshHTML.slice(5000*(i-1), 5000*i) + arraytrans + refreshHTML.slice(5000*i+5000); 
                document.body.innerHTML = translatedHTML;
            }   

    })(i);
}

});

更新:我尝试了linostar的方法,虽然它确实取代了预期的HTML,但它完全搞砸了页面的格式。我应该采取不同的方法吗?

(function (i) {
    var translatetext = document.body.innerHTML.substring(5000*i, (5000*i)+5000);
    //call an Async API to translatetext

    //callback for async API call
        {
        var translation = xmlhttp2.responseText;
        var refreshHTML = document.body.innerHTML;

        if (i == 0)
            translatedHTML = arraytrans + refreshHTML.substring(5000*i+5000);
        else if (i == loops - 1)
            translatedHTML = refreshHTML.substring(0, 5000*i) + arraytrans;
        else
            translatedHTML = refreshHTML.substring(0, 5000*i) + arraytrans + refreshHTML.substring(5000*i+5000);

        document.body.innerHTML = translatedHTML;
        }   
    })(i);

1 个答案:

答案 0 :(得分:-1)

为什么在刷新HTML上使用slice函数? slice用于从数组中剪切部分,而不是在数组中使用它。

请改用以下内容:

if (i == 0)
  translatedHTML = arraytrans + refreshHTML.substring(5000*i+5000);
else if (i == loops - 1)
  translatedHTML = refreshHTML.substring(0, 5000*i) + arraytrans;
else
  translatedHTML = refreshHTML.substring(0, 5000*i) + arraytrans + refreshHTML.substring(5000*i+5000);