所以我有这段代码:
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(){}
?
答案 0 :(得分:3)
函数this
内部意味着其他内容。你可以抓住它:
this.someotherelement = $("someotherelement");
var _this = this;
this.someelement.fadeOut(500, function(){
_this.someotherelement.attr("title", "something");
_this.someelement.fadeIn(500);
});
答案 1 :(得分:1)
这是由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);
});
}
答案 2 :(得分:0)
我已经编辑了你的代码,我希望它有所帮助。
function theObject(){
var someelement = $("#someelement");
var someotherelement = $("#someotherelement");
someelement.fadeOut(500, function(){
someotherelement.attr("title", "something");
someelement.fadeIn(500);
});
}
答案 3 :(得分:0)
是某种身份证?如果是这样,你错过了一个#...
this.someotherelement = $("#someotherelement");