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++);
});
}
}
}
当用户单击 div 时,我会得到 this.ZIndex 的“Nan”,因此我的“change-zindex-on-click”功能不起作用。为什么它没有得到认可,我怎样才能让它发挥作用?
我认为这与 jquery 的 $() 函数有关,因为 this.Windows[i] 在该 block 内也未定义。
点击“lol”div 看看会发生什么
提前致谢
最佳答案
因为在您的单击事件内部,this
是您单击的元素,而不是 WM 对象。
最简单的修复方法是提前绑定(bind)
点击函数的this
值:
$("#" + this.Windows[i]).click(function () {
alert("#"+this.id + ":" + this.ZIndex++);
$("#" + this.id).css("z-index", this.ZIndex++);
}.bind(this);
<小时/>
编辑 - 结果你想读取被单击元素的 id
属性,因此上面的方法在这种情况下可能不起作用,因为你仍然需要 this.id
来引用 dom 元素的 id。
肯定要学会如何使用function.bind,但是对于这个问题,下面的解决方案就是你想要的
<小时/>当然,这在 IE8 中不起作用(没有填充程序),所以如果这是一个问题,您可以提前保存 WM 对象的 this
值并使用 that 在点击处理程序中:
this.Initialize = function() {
var self = this;
for (var i = 0; i < this.Windows.length; i++) {
$("#" + this.Windows[i]).click(function () {
alert("#"+ this.id + ":" + self.ZIndex++);
$("#" + this.id).css("z-index", self.ZIndex++);
});
}
}
关于javascript - jquery 的 click() 中 this.variable = NaN,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14800056/