html:
<div id="mydiv">lol</div>
javascript:
var oWM = new WM();
oWM.Add("mydiv");
oWM.Initialize();
function WM() {
this.ZIndex = 1000;
this.Windows = [];
this.Add = function(id) {
this.Windows.push(id);
}
this.Initialize = function() {
for (var i = 0; i < this.Windows.length; i++) {
$("#" + this.Windows[i]).click(function () {
alert("#"+this.id + ":" + this.ZIndex++);
$("#" + this.id).css("z-index", this.ZIndex++);
});
}
}
}
when the user clicks on the div i get a “Nan” for this.ZIndex, so my change-zindex-on-click function doesn’t work. Why doesn’t it get recognized and how can i make it work?
I think it has something to do with jquery’s $() function because this.Windows[i] is also undefined inside that block.
click on the “lol” div and see what happens
thanks in advance
Because inside of your click event,
thisis the element you clicked on, not the WM object.The simplest fix would be to
bindthe click function’sthisvalue ahead of time:EDIT – turns out you want to read the
idproperty off of the element that was clicked, so the above probably won’t work in this case since you still needthis.idto refer to the dom element’s id.Definitely learn how to use function.bind, but for this problem, the solution below is what you want
Of course this won’t work in IE8 (without a shim) so if that’s a problem, you can just save the
thisvalue of your WM object ahead of time and use that in the click handler: