.Parent() within beforeSend

Asked

Viewed 28 times

0

I have the following code:

// JavaScript Document
$(document).ready(function(e) {

  $("a.excluiAdmin").click(function() {

        if (confirm('Deseja Excluir este Administrador?') ) {

        var link = $(this);

        $.ajax({
            url: "../_requeridos/excluiAdministrador.php",
            type: 'POST',            
            data : {
                    'administradorid'   : $(this).attr('administradorid')
                   },
            beforeSend: function() {

              $(link).html("<img src='../_img/_bannerImgs/spinner.gif' />")

            },
            success: function (retorno) {

                if (retorno == 1) {

                    alert('Excluido com sucesso');
                    location.reload();

                } else {

                    alert("Erro na exclusão");

                }

            },
            cache: false,
        });

        return false;

      }

  })


});

Within the confirm i do:

   var link = $(this);

Then I take the this of object who suffers the action;

And in the beforeSend doing:

    beforeSend: function() {

      $(link).html("<img src='../_img/_bannerImgs/spinner.gif' />")

    },

So I can get the html of the element a who will receive the action.

I wonder if you could do something like

      alert($(this).before($(this)).html())

And not depend on doing

var link = $(this);

it is possible that?

1 answer

0

Basically, it is necessary to use var algo = $(this);, due to the scope of the operation.

When you access the event scope click(), and tries to access another scope, automatically the JS will understand that this $(this) is of current scope.

Examples

in this function, I need to define the variable, to retrieve the object from the previous scope

$("div").on("click", function(){
    alert($(this)); //div

    $("div2").on("click", function(){
       alert($(this)); //div2
    });
}); 

In a more dynamic example (taken from Mozilla Developer).

The value of this is determined according to the function called.

var test = {
  prop: 42,
  func: function() {
    return this.prop;
  },
};

console.log(test.func());
// expected output: 42

Alternative

Use bind to create a new function with the same scope as the original object.

function f() {
  return this.a;
}

var g = f.bind({a: 'azerty'});
console.log(g()); // azerty

var h = g.bind({a: 'yoo'}); // bind only works once!
console.log(h()); // azerty

var o = {a: 37, f: f, g: g, h: h};
console.log(o.f(),o.f(), o.g(), o.h()); // 37,37, azerty, azerty

Sources

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this#The_bind_method

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/bind

  • so the way I did it’s still more readable and less code!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.