繁体   English   中英

jQuery访问父对象属性?

[英]jQuery access parent object attribute?

所以我有这段代码:

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

由于某种原因, this.someotherelement是未定义的。 我猜是因为它包装在function(){}

在函数内部, this意味着其他内容。 您可以捕获它:

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

这是由JavaScript作用域问题引起的。 创建函数创建一个新的作用域this使得this指的是功能。 您可以通过执行以下操作来修复它:

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); 
  });
}

我已经编辑了您的代码,希望对您有所帮助。

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

是另一个ID吗? 如果是这样,则说明您缺少#...

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM