所以我有一个脚本需要遍历父 DIV
中的每个 P
标签,类名是 entry-content
并使用谷歌翻译 API 翻译每一个。
所以当用户点击一个链接将页面从英语翻译成西类牙语时,这个函数就会运行:
function spanish() {
$(".entry-content p").each(function(){
var text = $(this).html();
google.language.detect(text, function(result) {
google.language.translate(text, "en", "es", function(result) {
if (result.translation) {
alert($(this).html()); //outputs NULL
$(this).html(result.translation); //doesn't work
}
});
});
});
}
问题是当 iIget 到内部函数 $(this).html()
返回 NULL 并且我无法更改当前元素 html 以将其更改为新的翻译文本.
所以我想我的问题是: 如何将当前选定的元素传递给嵌套函数?
谢谢
最佳答案
你可以将它存储在一个局部变量中
this
的值将始终与调用函数的上下文相关。在您的示例中,您将一个函数传递给 google.language.translate
,因此大概是 google.language.translate
调用了该函数。
但是,如果当 $(this)
是您的 p
时存储它的值,您将能够从回调函数中使用该变量。
function spanish() {
$(".entry-content p").each(function(){
var $this = $(this);
var text = $this.html();
google.language.detect(text, function(result) {
google.language.translate(text, "en", "es", function(result) {
if (result.translation) {
alert($this.html()); //outputs NULL
$this.html(result.translation); //doesn't work
}
});
});
});
}
关于javascript - 将 $(this) 选择器传递给嵌套函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4501627/