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 this
will always relate to the context in which the function is called. In your example, you're passing a function to google.language.translate
, and so presumably, it is google.language.translate
that calls that function.
However, if you store the value of $(this)
when it is your p
, you will be able to use that variable from the callback function.
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
}
});
});
});
}
It's because this
changes context in that callback, just keep a reference to the element/object you want, like this:
function spanish() {
$(".entry-content p").each(function(){
var text = $(this).html(), self = this;
google.language.detect(text, function(result) {
google.language.translate(text, "en", "es", function(result) {
if (result.translation) {
$(self).html(result.translation);
}
});
});
});
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With