当我比较以下情况时,我感到惊讶:
button = document.getElementById("addSugerenciaButton");
if (button != null) {
button.onclick = "post_to_url('" + addSugerenciaURL + "', idBuzon', '" + id + "');";
}
button = document.getElementById("removeBuzonButton");
if (button != null) {
button.onclick = function() {
if (!confirm(removeSugerenciaMessage)) {
return false;
};
post_to_url(removeBuzonURL, 'idBuzon', id);
};
}
button = document.getElementById("editBuzonButton");
if (button != null) {
button.setAttribute("onclick","post_to_url('" + editBuzonURL + "', 'idBuzon', '" + id + "');");
}
只有后者似乎改变了HTML(至少使用Firebug进行检查),而其余部分虽然也正常工作,但在editBuzonButton元素中没有显示任何onclick事件。
这是为什么呢?有任何想法吗?
addEventListener
/attachEvent
添加事件处理程序是没有问题的。事实上,这通常更可取:首先,它在各种浏览器中几乎统一处理(除了IE需要通过window.event
访问事件对象);其次,this
始终是对原始元素的引用(与attachEvent
不同);第三,阻止事件的默认操作只需要return false;
而不是evt.preventDefault()
/evt.returnValue = false
。 - Tim Down