原型等效于jQuery live函数
我需要通过给定的css选择器将事件侦听器绑定到所有动态创建的元素。
在jQuery中,那就是
$(".foo").live("click", function(e) { // bar });
原型中是否有相应的等价物?
这通常使用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() } });
这个问题的正确答案在这里: 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关键字将始终引用原始元素(在本例中为文档)。