Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing $(this) selector into nested functions

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

like image 738
Jamie Avatar asked Jan 20 '23 21:01

Jamie


2 Answers

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
            }
          });
        });
      });
}
like image 172
David Hedlund Avatar answered Jan 27 '23 18:01

David Hedlund


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);
        }
      });
    });
  });
}
like image 31
Nick Craver Avatar answered Jan 27 '23 20:01

Nick Craver