2010-07-22 4 views
0

J'ai donc ce code:Attribut d'objet parent jQuery access?

function theObject(){ 
    this.someelement = $("#someelement"); 
    this.someotherelement = $("someotherelement"); 
    this.someelement.fadeOut(500, function(){ 
     this.someotherelement.attr("title", "something"); 
     this.someelement.fadeIn(500); 
    }); 
} 

pour une raison quelconque this.someotherelement est définie. Je devine parce qu'il est enveloppé dans un function(){}?

+0

Est-ce l'ID de l'élément? Il vous manque un signe #. – Adam

+0

publie aussi une partie du code html pertinent, donc ce sera plus clair ... – gillyb

+1

A l'intérieur de la fonction, 'this' fait référence à' this.someelement' (en fait à son élément DOM). Avec la plupart des fonctions jQuery (toutes?) Qui prennent un rappel, 'this' fait référence à l'élément (DOM) sur lequel vous appelez la fonction. –

Répondre

1

Cela est dû à un problème de cadrage JavaScript. La création d'une fonction crée une nouvelle portée pour this qui fait référence à la fonction this. Vous pouvez le réparer en faisant ... cela:

function theObject(){ 
    this.someelement = $("#someelement"); 
    this.someotherelement = $("someotherelement"); 

    // bind this to that (what?). This way, this will still be accessible inside 
    // the new function's scope as that 
    var that = this; 
    this.someelement.fadeOut(500, function(){ 
    that.someotherelement.attr("title", "something"); 
    that.someelement.fadeIn(500); 
    }); 
} 
3

A l'intérieur de la fonction this signifie autre chose. Vous pouvez le capturer si:

this.someotherelement = $("someotherelement"); 
var _this = this; 
this.someelement.fadeOut(500, function(){ 
    _this.someotherelement.attr("title", "something"); 
    _this.someelement.fadeIn(500); 
}); 
+0

Au lieu de '_this.someelement' vous pouvez aussi utiliser' $ (this) '. –

0

J'ai modifié votre code, j'espère que cela aide.

function theObject(){ 
    var someelement = $("#someelement"); 
    var someotherelement = $("#someotherelement"); 
    someelement.fadeOut(500, function(){ 
     someotherelement.attr("title", "something"); 
     someelement.fadeIn(500); 
    }); 
} 
0

est someotherelement an ID? Si oui, il vous manque un # ...

this.someotherelement = $("#someotherelement");