【发布时间】:2010-12-01 13:48:16
【问题描述】:
我需要通过给定的 css 选择器将事件监听器绑定到所有动态创建的元素。
在 jQuery 中,就是
$(".foo").live("click", function(e) {
// bar
});
Prototype 中是否有任何等价物?
【问题讨论】:
标签: javascript jquery events prototypejs
我需要通过给定的 css 选择器将事件监听器绑定到所有动态创建的元素。
在 jQuery 中,就是
$(".foo").live("click", function(e) {
// bar
});
Prototype 中是否有任何等价物?
【问题讨论】:
标签: javascript jquery events prototypejs
这通常使用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()
}
});
【讨论】:
live 被引入以来,这就是 jQuery 在实时绑定的底层工作方式。 jQuery 可以将处理程序绑定到 document 以处理不原生传播的事件,因为 jQuery 将手动创建和传播此类事件。
el 需要分配而不是比较:)
问题的正确答案在这里: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 关键字将始终引用原始元素(在本例中为文档)。
【讨论】:
document.on(...),您必须以同样的方式使用Event.on(document, ...)。
document.on,当在控制台中检查时,它返回undefined。事实证明,Prototype 1.7 的站点正在运行 Prototype 1.6!我必须check the source 才能找到它已定义。