fro*_*tto 7 javascript jquery event-handling javascript-events
我在java脚本中模拟了一个类,它的代码在这里:
function myclass()
{
this.count ;
this.init = function(){
$("div.mybtn").click({n:this},function(e){
e.data.n.count++;
});
}
this.getCount = function(){
alert(this.count);
}
}
Run Code Online (Sandbox Code Playgroud)
然后我创建了这个类的实例并执行了它的方法init(),但是当我点击任何div.mybtn元素时,它没有增加它的值this.count.
似乎对象this是通过值而不是通过引用传递给事件处理程序的.
我如何通过引用将变量传递给事件处理程序?
谢谢你的帮助
Javascript 没有按引用传递参数。对于你想要的,你应该使用闭包变量:
this.init = function(){
var self = this;
$("div.mybtn").click(function(){
self.count++;
});
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
10316 次 |
| 最近记录: |