我有一位同事问我为什么他无法从回调函数访问事件参数。事实证明,jquery 似乎在调用完成后将事件设置为 null,并创建一个临时局部变量解决了问题(见下文)。
然后这让我思考,为什么“消息”甚至可以用于回调。有人可以解释一下吗?
$('some seletor').click({msg: message},function(event){
alert(event.data.msg); //event.data.msg is not available to the json callback because event is null
var message = event.data.msg; //message will be available to the callback...why?
$.getJSON('ajax/test.json', function(data) {
alert(message); //works ok - why is the message variable visible here at all, should it not have gone out of scope when the above function ended?
alert(event.data.msg); //will crash, seems that event has been set to null by the framework after the function finished
});
});
Run Code Online (Sandbox Code Playgroud)
给定范围内存在的任何变量均可用于该范围内定义的所有函数。(这就是在 JS 中定义范围的方式,如果您想了解其定义的细节,语言规范的这一部分可能是一个很好的切入点)。
由于定义回调的函数表达式位于定义变量的函数内部,因此该变量对其可用。
| 归档时间: |
|
| 查看次数: |
857 次 |
| 最近记录: |