为什么事件对象不同来自jquery bind和addEventListener

时间:2022-08-23 23:56:53

Why is it when I use the jQuery bind the event object I get back is different from the event object I get back using addEventListener?

为什么当我使用jQuery绑定我返回的事件对象时,我使用addEventListener返回的事件对象不同?

The event object resulting from this jQuery bind does not have the targetTouches array (among other things) but the event from the addEventListener does. Is it me or is something not right here?

此jQuery绑定产生的事件对象没有targetTouches数组(除其他外),但addEventListener中的事件没有。是我还是不对的?

$(document).ready (function () {
    $("#test").bind("touchmove", function (event) {
        console.log(event.targetTouches[0].pageX);
        // targetTouches is undefined
    });
});

vs.

$(document).ready (function () {
    var foo = document.querySelectorAll('#test')
    foo[0].addEventListener('touchmove', function (event) {
        console.log(event.targetTouches[0].pageX);
        // returns the correct values
    }, false);
});

1 个解决方案

#1


24  

That's because jQuery uses its own Event model.

那是因为jQuery使用自己的Event模型。

jQuery simply copies and normalizes some properties from the original event, to the event object that you get as the first argument of the handler.

jQuery只是简单地将原始事件中的一些属性复制并规范化为您作为处理程序的第一个参数获得的事件对象。

The copied properties are based on the DOM Level 3 Events Spec.

复制的属性基于DOM Level 3 Events Spec。

To get the original event object, you can:

要获取原始事件对象,您可以:

$(document).ready (function () {
    $("#test").bind("touchmove", function (event) {
        var e = event.originalEvent;
        console.log(e.targetTouches[0].pageX);
    });
});

The originalEvent property is accessible and it will work, but is not documented, you can see how it's set behind the scenes in the jQuery.Event constructor.

原始事件属性是可访问的,它可以工作,但没有记录,你可以看到它是如何在jQuery.Event构造函数的幕后设置的。

#1


24  

That's because jQuery uses its own Event model.

那是因为jQuery使用自己的Event模型。

jQuery simply copies and normalizes some properties from the original event, to the event object that you get as the first argument of the handler.

jQuery只是简单地将原始事件中的一些属性复制并规范化为您作为处理程序的第一个参数获得的事件对象。

The copied properties are based on the DOM Level 3 Events Spec.

复制的属性基于DOM Level 3 Events Spec。

To get the original event object, you can:

要获取原始事件对象,您可以:

$(document).ready (function () {
    $("#test").bind("touchmove", function (event) {
        var e = event.originalEvent;
        console.log(e.targetTouches[0].pageX);
    });
});

The originalEvent property is accessible and it will work, but is not documented, you can see how it's set behind the scenes in the jQuery.Event constructor.

原始事件属性是可访问的,它可以工作,但没有记录,你可以看到它是如何在jQuery.Event构造函数的幕后设置的。