我正在尝试用jQuery翻译一些短语。这段代码非常有效:
changeText = function(text, newText){
var currentText = $('span.example').html();
$('span.example').html(currentText.replace(text,newText)); };
window.setTimeout(function(){changeText("TranslateMe", "Translation")}, 0000);
然而,当你等待ajax生成的结果时,它几乎没用。澄清一下 - 这是一个搜索脚本,其程序如下:
单击“搜索”时,会“正常”加载页面的一部分。我可以毫无问题地更改这些文本字符串。
之后有结果通过ajax动态加载结果我猜是有div“块”一个接一个地加载。这些短语无法翻译。
解决方法是等待一段时间,直到所有内容都被加载,然后它才能用于某些部分。 E. g。:
window.setTimeout(function(){changeText("TranslateMe", "Translation")}, 20000);
但是,这不是一个好的解决方案,因为用户会在一段时间内看到未翻译的字符串。
因此,我正在寻找一种能够在显示字符串时更改字符串的解决方案。有没有办法做到这一点?
提前致谢!
编辑:
尝试查理的方法:
<script>
changeText = function(text, newText, $el) {
$el.html(function(i, currentText){
return currentText.replace(text, newText);
});
};
$(function(){
changeText(text, newText,$('span.example'));
});
$.ajax({
success:function(data){
var $changeEl=$(data).find('span.example');
changeText(text, newText,$changeEl);
var currentText = $('span.example').html();
$('span.example').html(currentText.replace(TranslateMe,Translation));
};
})
})
</script>
答案 0 :(得分:0)
答案 1 :(得分:0)
我同意Tyron的意见,如果可以的话,你应该为AJAX调用添加或修改回调函数。
用于检测更改和转换而无需访问ajax。这样的事情可能有所帮助。
var c = document.getElementById('[ID OF CONTAINER FOR UNTRANSLATED BLOCKS]');
c.__appendChild = c.appendChild;
//this function catches the element before it is appended
c.appendChild = function(){
//this applies the change
c.__appendChild.apply(c, arguments);
var newBlock = $(c).children().last();
//this hides the newly added block
newBlock.hide();
// now perform your translations on the newBlock contents
//here
// and then make the block visible again
newBlock.show();
};
答案 2 :(得分:0)
如果更改函数以添加上下文参数,则可以执行以下操作:
changeText = function(text, newText, $el) {
/* html method allows for function as argument to modify element*/
$el.html(function(i, currentText){
return currentText.replace(text, newText);
});
};
然后在页面加载:
$(function(){
changeText( text, newText,$('span.example'));
});
在AJAX中成功寻找新元素并对其进行修改:
$.ajax({
success:function(data){
var $changeEl=$(data).find('span.example');
changeText( text, newText,$changeEl);
/* your code that inserts the new html here*/
})
})