HTML 通过 element.setAttribute("onclick","alert("Test");") 和 element.onclick = "alert("Test");" 进行更改;
在比较以下情况时,我感到很惊讶:
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 事件。
有什么想法为什么会发生这种情况吗?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
是的。
setAttribute
将属性添加到 Element DOM 节点。对于onclick
属性,添加onclick
事件处理程序会产生副作用,该处理程序是通过将属性值“编译”到 JavaScript 函数中来实现的。直接将函数分配给元素的
onclick
属性会附加处理程序,但不会自动向 DOM 节点添加属性。现在,有些浏览器可能不区分添加属性和直接附加处理程序。但请记住,虽然修改文档可能会创建可编写脚本的对象作为副作用,但情况并非如此:以编程方式创建 DOM 结构可能会也可能不会根据您碰巧使用的浏览器更改文档底层的 HTML 。
Yes.
setAttribute
adds an attribute to an Element DOM node. For theonclick
attribute, there is a side effect under the covers of also adding anonclick
event handler, which is made by 'compiling' the attribute value into a javascript function.Assigning a function to the
onclick
property of the element directly does attach the handler, but does not automatically add an attribute to the DOM node.Now it is possible that there are browsers that do not make the distinction between adding the attribute and attaching the handler directy. But keep in mind that although modifying the document may create scriptable objects as side effect, the reverse does not have to be the case: programmatically creating DOM structures may or may not change the HTML underlying the document according to the browser you happen to be using.
错误的。
您应该使用
addEventListener
/attachEvent
。例如:
Wrong.
You should use
addEventListener
/attachEvent
.For example:
在浏览器中的 JavaScript 中,如果可以避免属性,那么最好不要与属性有任何关系,而这几乎总是可以避免。对于事件处理程序属性,IE 的行为与所有其他浏览器不同(请参阅 为什么使用 setAttribute 设置的 onclick 属性无法在 IE 中工作? 对此进行讨论)。尽可能使用属性,除非您可能需要多个事件处理程序,否则最简单的选择是使用旧的 DOM0 事件处理程序属性并确保为它们分配一个函数。在这种情况下,使用您的最后一个示例:
In JavaScript in browsers, you're much better off not having anything to do with attributes if you can possibly avoid it, which you almost always can. In the case of event handler attributes, IE behaves differently to all other browsers (see Why does an onclick property set with setAttribute fail to work in IE? for a discussion on this). Just use properties wherever you can, and unless there's a possibility you will need multiple event handlers, the easiest option is to use the old DOM0 event handler properties and make sure you assign them a function. In this case, using your last example: