原型等效于jQuery live函数

Jak*_*old 15 javascript jquery events prototypejs

我需要通过给定的css选择器将事件侦听器绑定到所有动态创建的元素.

在jQuery中,那就是

$(".foo").live("click", function(e) {
   // bar
});
Run Code Online (Sandbox Code Playgroud)

原型中是否有相应的等价物?

kan*_*gax 22

这通常通过以下方式完成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()
  }
});
Run Code Online (Sandbox Code Playgroud)


rob*_*ert 13

这个问题的正确答案在这里:http://gurde.com/2011/08/jquery-live-in-prototype/

.live()Prototype中jQuery的等价物是Event.on()方法:

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();
Run Code Online (Sandbox Code Playgroud)

在回调中,this关键字将始终引用原始元素(在本例中为文档).