Is there any Prototype Javascript function similar

2019-08-14 20:25发布

问题:

Event.observe(window,"load",function() { $$(".elem_classs").findAll(function(node){ return node.getAttribute('title'); }).each(function(node){ new Tooltip(node,node.title); node.removeAttribute("title"); }); });

Using above method, I can retrieve all elements having ".elem_class" and apply some javascript functions on them. But I have a modal/popup box which has some elements also having ".elem_class" and these dont get in the scope of findAll/each as they are loaded into the dom thru ajax.

How do I apply the same to dynamically loaded elements as well? I am using Prototype Library. (I have used JQuery's Live function which keeps track of all future elements, but need to achieve something similar using Prototype)

Thanks.

回答1:

As far as I know, event delegation is bot built into Prototype, but it shouldn't be too difficult to do on your own. Simply add a handler to observe the event on the body then use Event#findElement to check if it matches your selector.

Here is a sample function that sets up the delegation for you (run this on load):

/**
 * event_type: 'click', 'keydown', etc.
 * selector: the selector to check against
 * handler: a function that takes the element and the event as a parameter
 */
function event_delegator(event_type, selector, handler) {
  Event.observe(document.body, event_type, function(event) {
    var elt = Event.findElement(event, selector);
    if (elt != document)
      handler(event, elt);
  });
}

You could probably extend Element to handle this for you, streamlining everything. Hope this helps!

Edit: The hover event (or mousein/mouseout) should be a good event for a tooltip. Also, don't get all the elements on load, that's unnecessary when using event delegation. Here's a link to more about event delegation: http://www.sitepoint.com/blogs/2008/07/23/javascript-event-delegation-is-easier-than-you-think/