javascript 原型 - 按元素类名点击事件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3945663/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Prototype - click event by element class name
提问by David
I am new to the prototype framework and am trying something really simple and failing. I am trying to respond to a click event on a button like so:
我是原型框架的新手,正在尝试一些非常简单但失败的事情。我正在尝试响应按钮上的点击事件,如下所示:
$$('.btn').observe('click', respond);
function respond(event) {
alert("hello");
}
Why isn't this working? Please help!
为什么这不起作用?请帮忙!
回答by Diodeus - James MacFarlane
Unlike jQuery, handing selectors with multiple results in Prototype works a little differently. You need to handle each selected result separately using .each().
与 jQuery 不同,在 Prototype 中处理具有多个结果的选择器的工作方式略有不同。您需要使用.each().
$$('.btn').each(function(element) {
element.observe('click', respond);
})
This is one of the reasons I moved over to jQuery. The other reason: knowing jQuery is marketable and knowing Prototype is not.
这是我转向 jQuery 的原因之一。另一个原因:了解 jQuery 是有市场价值的,而了解 Prototype 则不是。
回答by acme
Can be also be done with a single-liner, as someone already suggested in a comment:
也可以用单线完成,正如有人在评论中已经建议的那样:
$$('.btn').invoke('observe', 'click', respond);

