modify event data during propagation

后端 未结 3 728
心在旅途
心在旅途 2020-12-05 17:06

Is there any way of attaching data to a jQuery event object as it propagates up the DOM?

To clarify, if you have three nested divs, each with a click event listener

相关标签:
3条回答
  • 2020-12-05 17:58

    The event object that is passed by jQuery is a wrapper around the native event object. The bubbling happens at the javascript/browser level and hence the native event object seems to be shared among all the event handlers.

    $('div').click(function(e) {
        e.originalEvent.attribute =  (e.originalEvent.attribute || "") + 
            " " + $(this).prop("className");
        alert(e.originalEvent.attribute);
    });
    

    Tested in Chrome, Firefox, Safari, IE9 and IE10. If you test in other browsers please comment with the results.

    Here's the fiddle: http://jsfiddle.net/5AQqD/

    0 讨论(0)
  • 2020-12-05 18:06

    Although you cannot attach data directly to the event, you could still attach data to the targetElement via jQuery's data():

    $('div').click(function(e) {
        var info = $(e.target).data('info') || '';
        $(e.target).data('info', info + ' ' + $(this).attr('class'));
    });
    

    Here's the fiddle: http://jsfiddle.net/eKVmU/

    0 讨论(0)
  • 2020-12-05 18:09

    Maybe I've misunderstood the question, but I came across this StackOverflow page whilst searching for a way to do the same thing.

    I have since found that you can return the value/values that you want to pass at the end of each handler and then access them in subsequent handlers using the event.result property?

    Simple demo at http://api.jquery.com/event.result/

    0 讨论(0)
提交回复
热议问题