Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
738 views
in Technique[技术] by (71.8m points)

javascript - Listen for jQuery Event With Vanilla JS

So I am trying to determine whether its possible to listen for events added with jQuery using vanilla JS. I found this question:

Listen to jQuery event without jQuery

which definitely answers it for version 1 of jQuery. How about version 3 however?

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:

var $input1 = $("#input1");
var $input2 = $("#input2");
var input1 = document.getElementById("input1");
var input2 = document.getElementById("input2");

var event1 = "event1";
var event2 = "event2";

$("#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!");
});
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.

So in summary, jQuery can catch vanilla JS events, but vanilla JS cannot catch jQuery added events.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...