admin管理员组

文章数量:1427301

I was wondering how to achieve jQuery's .live functionality with "traditional" JavaScript. I want something like $('a').live('mouseover', mouseover_func) to be written as usual JavaScript. But how?

I was wondering how to achieve jQuery's .live functionality with "traditional" JavaScript. I want something like $('a').live('mouseover', mouseover_func) to be written as usual JavaScript. But how?

Share Improve this question asked Feb 13, 2011 at 16:19 Rainer ZufallRainer Zufall 611 bronze badge
Add a ment  | 

2 Answers 2

Reset to default 10

Bind a "mouseover" event handler to the <body> element. In that handler, check the "target" property of each event it catches and see whether its "tagName" property is "A". If so, call the handler.

The "live" feature leverages event "bubbling", which is the name for the browsers process of checking for handlers from the target element to the root of the DOM, one parent at a time. Since each <a> in your document can ultimately be traced back up to the <body>, that root node will get all the "mouseover" events that aren't shunted off by lower-level handlers that cancel bubbling (via the "stopPropagation()" method on the event object, or some weird browser-specific way I guess).

Not all events bubble, however. I'm looking around for a good reference ... ok here, the MDC page seems pretty good though a little old maybe.

Just read the jQuery source code to see how it does it. That's one of the joys of open source. You will learn an awful lot...

本文标签: javascriptjQuery39s live functionality without jQueryStack Overflow