Prototype equivalent for jQuery live function

前端 未结 2 1263
遥遥无期
遥遥无期 2020-12-01 04:01

I need to bind event listener to all dynamicaly created elements by given css selector.

In jQuery, that would be

$(\".foo\").live(\"click\", function         


        
相关标签:
2条回答
  • 2020-12-01 04:22

    This is usually done with Event#findElement:

    document.observe('click', function(e, el) {
      if (el = e.findElement('.foo')) {
        // there's your `el`
        // might want to stop event at this point - e.stop()
      }
    });
    
    0 讨论(0)
  • 2020-12-01 04:31

    The correct answer to the question is here: http://gurde.com/2011/08/jquery-live-in-prototype/

    The equivalent of the jQuery .live() in Prototype is the Event.on() method:

    var handler = document.on(
        'click',
        'div[id^="post-"] .attached-post-thumbnail',
        function(event, element) {
            console.log(this);
            console.log(element);
        }.bind(this)
    );
    
    handler.stop();
    handler.start();
    

    Within the callback, the this keyword will always refer to the original element (in this case document).

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