简体   繁体   English

event.currentTarget问题

[英]event.currentTarget issue

I was debugging an issue in my javascript code with a variable not being properly set. 我正在调试我的javascript代码中的一个问题,其中一个变量未正确设置。 After a little research, I found out that the variable was not being populated because it was taking its value from an event property that didn't exist. 经过一番研究后,我发现变量没有被填充,因为它从一个不存在的事件属性中获取了它的值。 In this case, it was deriving its value from event.currentTarget, which was strangely null. 在这种情况下,它从event.currentTarget派生它的值,它奇怪地为null。

So I'm a little baffled now. 所以我现在有点困惑。 I always though that event.currentTarget always pointed to whatever element held the listener that fired the event. 我总是认为event.currentTarget总是指向持有触发事件的侦听器的任何元素。 So under what circumstances would event.currentTarget actually be null? 那么在什么情况下event.currentTarget实际上是null?

All right, I finally figured this out. 好吧,我终于想通了。

The problem was with the way the event was being handled. 问题在于事件的处理方式。 As you can see below, the event object itself was not only to be processed by its respective handler function; 如下所示,事件对象本身不仅要由其各自的处理函数处理; it was also going to be processed by another function that was invoked only when an AJAX call that was made in the handler returned successfully. 它也将由另一个函数处理,该函数仅在处理程序中进行的AJAX调用成功返回时调用。 However, once the success function executes under the AJAX call, the event object loses some of its context, namely its currentTarget property. 但是,一旦成功函数在AJAX调用下执行,事件对象就会失去一些上下文,即currentTarget属性。 I presume that the reason why this is is because we're not directly within the scope of the handler once the browser starts executing code within the success function. 我认为这是因为一旦浏览器开始在success函数中执行代码,我们就不会直接在处理程序的范围内。

$('#element').click(function(e) {

    // bunch of lines of code here

    $.ajax({
       type: 'POST',
       url: // url,
       ...,
       success: function(response) {

           // more lines of code here

           callAnotherFunction(e);
           // When we invoke the above function, we pass the event in as a 
           // parameter, but the event has already lost some of its context
           // due to scope change.
       }
    });

})

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM