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
380 views
in Technique[技术] by (71.8m points)

javascript - modify event data during propagation

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, then clicking on the innermost div results in all three handlers being called from the innermost to the outermost (event propagation 101). What I'd like to do is add some data to the event object in each handler that's accessible to the next layer up.

How do I do that?

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

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/


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

...