我在单个页面上有各种元素。他们共享一个类。 我想使用原型(prototype)在所有这些元素上添加一个 onclick 事件。
对于 id 我可以做这样的事情:
Event.observe(window, 'load',
function() {
$('id_of_the_element').addEventListener('onclick',any_function,true);
}
);
如果我们有元素的 id,这很好。我想使用 CSS 类做同样的事情,因为所有元素共享同一个类。
更新:
document.observe("dom:loaded", function() {
$$('.message').invoke('observe', 'click', hide_all_messages)
});
function hide_all_messages()
{
$$('.message').hide();
}
这是行不通的。
错误:
hide is not a function
最佳答案
$$('.myClass').each(
function(element){
Event.observe("click",element,any_function);
}
);
你明白了!
关于javascript - 在CSS class的基础上为各种元素添加onclick事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3708472/