简体   繁体   中英

What am I missing about jQuery's trigger and event.data?

I am not able to cause jQuery.trigger to send data accessible via event.data in my click handler.

I wonder if I fundamentally understand how these sets of functions are meant to operate?

Here is my JS:

$(document).ready(function() {

    $("#bb").click(function(event){
      console.log(event.data);
    });

$("#bb").trigger("click", {key: "val"});

});

And here my HTML:

<button id="bb" value="click me">click me</button>

As you can see, it's pretty straightforward. What I expect to see in the console is {key: "val"}, but what I am seeing is null.

Here is a codepen for your utility. https://codepen.io/crowns/pen/ZEYxEEO?editors=1111


I have a point of confusion about the jQuery documentation on trigger. It

Note the difference between the extra parameters passed here and the eventData parameter to the .on() method. Both are mechanisms for passing information to an event handler, but the extraParameters argument to .trigger() allows information to be determined at the time the event is triggered, while the eventData argument to .on() requires the information to be already computed at the time the handler is bound.

How is one ought to access the data passed to trigger via the extraParameters arguement?

And is eventData set via on accessible by Event.data? To answer my own question, yes, based on reading documentation for on().

The first parameter passed is always event , the second one is the data you're sending - You can't use .trigger() to change event.data

 $(document).ready(function() { $("#bb").on('click', function(event, data) { console.log(event.data); console.log(data); }); $("#bb").trigger('click', {key: 'value'}); });
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <button id="bb" value="click me">click me</button>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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