.parent () within beforeSend

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 confirm I do:

   var link = $(this);

Then I get the this of the object that undergoes the action;

And in beforeSend I do:

    beforeSend: function() {

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

    },

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

I would like to know if you have something like

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

And do not depend on doing

var link = $(this);

Is this possible?

    
asked by anonymous 03.06.2018 / 17:40

1 answer

0

Basically, you need to use var algo = $(this); , due to the scope of the operation.

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

Examples

In this function, I need to set 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 by the called function.

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

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

Alternative

Use bind, allowing you 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

link

link

    
03.06.2018 / 18:55