0

bing V2 javascript api 需要回调才能工作。使用jQuery动态添加脚本块(忽略全局命名空间的污染):

function translate(text) {
    var txt = "text=" + text;
    var lang = "&to=fr";
    var appId = "&appid=apikey"; // Add your AppId here
    var func = "&oncomplete=window.translated";

    $("<script><\/script>")
                .attr("src", "http://api.microsofttranslator.com/V2/ajax.svc/Translate?" + txt + lang + appId + func)
                .appendTo("HEAD");
}

然后在多个元素上使用点击事件来触发翻译:

$(document).ready(function () {

    $('a').click(function () {
        var tr = $(this).parent().parent();
        var txtin = tr.find('.in').text();
        var out = tr.find('.out'); // would like translation inserted here
        translate(txtin);
        return false;
    });

});

最后是 api 所需的回调:

function translated(text) {
    $("#translation").text(text);
}

我想指定不同的元素来接收翻译的文本,具体取决于单击哪个元素来启动翻译 - 但是使用上述方法我不能将任何额外的参数传递给 bing,然后在回调中返回。

我应该如何重写它以允许单击 row1 中的 el 将翻译放入 row1 并单击 row2 中的 el 将翻译放入 row2?即在我的点击事件中使用分配给“out”的元素。

4

1 回答 1

1

回调方法不支持状态对象,因此您需要在某个全局位置跟踪您的对象。我已经实现了一个队列模型来帮助你实现它

  1. 在全局变量中添加队列定义为

    var queue = new Array();
    
  2. 在调用服务之前将您的“输出”对象添加到它

    $('a').click(function () { 
        var tr = $(this).parent().parent(); 
        var txtin = tr.find('.in').text(); 
        var out = tr.find('.out'); // would like translation inserted here 
        //Here it goes
        queue.push(out);
        ////////////////
        translate(txtin); 
        return false; 
    });    
    
  3. 将对象的索引附加到文本中,因为服务不翻译数字,它将返回给您。如果您一次不进行多个翻译,则可以跳过添加索引,这只是为了在某些服务调用比其他服务调用慢的情况下获得正确的对象。

    function translate(text) {
    
        //Here it goes             
        var txt = "text=" + text + " ___" + (queue.length - 1);     
        ////////////////    
        var lang = "&to=fr";             
        //...no more changes here   
    }
    
  4. 最后在回调方法中提取您的对象,并从翻译的文本中删除附加的索引和拆分器。

    function translated(text) {
    
        if (queue.length > 0) {
            var splts = text.split(' ___')
            var indx = splts[splts.length - 1];
            var out = queue[indx];
            //remove the out object from the queue
            queue.slice(indx, indx + 1);
            //remove the index number from the end of the word
            text = text.substr(0, text.lastIndexOf(indx) - 4);
            out.text(text);
        }
    }
    
于 2011-11-23T11:11:17.023 回答