原型等效于jQuery live函数

时间:2009-09-25 22:07:26

标签: javascript jquery events prototypejs

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

在jQuery中,那将是

$(".foo").live("click", function(e) {
   // bar
});

Prototype 中有没有相应的内容?

2 个答案:

答案 0 :(得分: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()
  }
});

答案 1 :(得分:13)

问题的正确答案如下:http://gurde.com/2011/08/jquery-live-in-prototype/

Prototype中jQuery .live()的等价物是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();

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