简体   繁体   English

原型 - 按元素类名称单击事件

[英]Prototype - click event by element class name

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! 请帮忙!

Unlike jQuery, handing selectors with multiple results in Prototype works a little differently. 与jQuery不同,在Prototype中处理具有多个结果的选择器的工作方式略有不同。 You need to handle each selected result separately using .each() . 您需要使用.each()分别处理每个选定的结果。

$$('.btn').each(function(element) {
    element.observe('click', respond);
})

This is one of the reasons I moved over to jQuery. 这是我转移到jQuery的原因之一。 The other reason: knowing jQuery is marketable and knowing Prototype is not. 另一个原因是:知道jQuery是可销售的并且知道Prototype不是。

也可以使用单线程来完成,正如有人在评论中已经建议的那样:

$$('.btn').invoke('observe', 'click', respond);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM