6 javascript event-handling javascript-events
我知道如果对象是一个函数,我可以使用闭包(var self = this)
<a href="#" id="x">click here</a>
<script type="text/javascript">
var object = {
y : 1,
handle_click : function (e) {
alert('handling click');
//want to access y here
return false;
},
load : function () {
document.getElementById('x').onclick = this.handle_click;
}
};
object.load();
</script>
Run Code Online (Sandbox Code Playgroud)
因此,事件处理程序部分连接得很好(我自己测试过),但是,正如您的评论所示,您无权访问刚刚定义的对象的“y”属性。
这有效:
var object = {
y : 1,
handle_click : function (e) {
alert('handling click');
//want to access y here
alert(this.y);
return false;
},
load : function () {
var that = this;
document.getElementById('x').onclick = function(e) {
that.handle_click(e); // pass-through the event object
};
}
};
object.load();
Run Code Online (Sandbox Code Playgroud)
还有其他方法可以做到这一点,但这是有效的。
| 归档时间: |
|
| 查看次数: |
7401 次 |
| 最近记录: |