使用Vanilla JS收听jQuery事件 [英] Listen for jQuery Event With Vanilla JS
问题描述
所以我试图确定是否可以使用vanilla JS来监听使用jQuery添加的事件。我发现了这个问题:
So I am trying to determine whether its possible to listen for events added with jQuery using vanilla JS. I found this question:
这肯定是jQuery版本1的答案。那么版本3怎么样?
which definitely answers it for version 1 of jQuery. How about version 3 however?
我有一个小提琴,我已经放在一起测试,但我无法让第一个提交与任何版本的jQuery一起使用。我错过了什么,或者jQuery 3中的事件模型仍然没有使用DOM事件模型?
I have a fiddle that I have put together to test out, but I am unable to get the 1st submit to work with any version of jQuery. Am I missing something, or is the event model in jQuery 3 still not using the DOM event model?
https://jsfiddle.net/ydej5qer/1/
以下是小提琴中的代码:
Here is the code in the fiddle:
HTML:
<div id="div1">
<p>
This is div1. My event was added via jQuery and is listened for by vanilla JS.
</p>
<p>
Enter the number 2 to have the event fired.
</p>
<input type="text" id="input1" />
<button id="button1">
Submit
</button>
</div>
<div id="div2">
<p>
This is div2. My event was added via vanilla JS and is listened for by jQuery.
</p>
<p>
Enter the number 2 to have the event fired.
</p>
<input type="text" id="input2" />
<button id="button2">
Submit
</button>
</div>
JavaScript:
JavaScript:
var $input1 = $("#input1");
var $input2 = $("#input2");
var input1 = document.getElementById("input1");
var input2 = document.getElementById("input2");
var event1 = "civicscienceEvent1";
var event2 = "civicscienceEvent2";
$("#button1").click(function() {
if (+$input1.val() == 2) {
$input1.trigger(event1, {message: "Event 1 triggered!"});
}
});
input1.addEventListener(event1, function(e) {
console.log("Event 1 triggered! message=" + e.detail.message);
});
$("#button2").click(function() {
if (+$input2.val() == 2) {
var event = new CustomEvent(event2, {detail: {message: "Event 2 triggered!"}});
input2.dispatchEvent(event);
}
});
$input2.on(event2, function(e) {
console.log("Event 2 fired, but I don't know how to get the message!");
});
推荐答案
简短的回答是,这是不可能的,因为jQuery提供香草JS上的事件层。这意味着vanilla JS无法与添加的层进行对话。
The short answer is that this is impossible as jQuery provides an event layer over vanilla JS. That means that vanilla JS cannot talk to that added layer.
总而言之,jQuery可以捕获vanilla JS事件,但是vanilla JS无法捕获jQuery添加的事件。
So in summary, jQuery can catch vanilla JS events, but vanilla JS cannot catch jQuery added events.
这篇关于使用Vanilla JS收听jQuery事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!