So I have a script in place that needs to go through each P tag within a parent DIV with the class name of entry-content and translate each one using the google translate API.
So when a user clicks a link to translate the page from english to spanish this function is run:
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
}
});
});
});
}
The problem is when iIget to the inner function $(this).html() comesback NULL and I am not able to change the current elements html in order to change it to the new translated text.
So I guess my question is:
How would I pass the current selected element into the nested functions?
Thanks
You may store it in a local variable
The value of
thiswill always relate to the context in which the function is called. In your example, you’re passing a function togoogle.language.translate, and so presumably, it isgoogle.language.translatethat calls that function.However, if you store the value of
$(this)when it is yourp, you will be able to use that variable from the callback function.