HTML更改为element.setAttribute("onclick","alert('Test');")和element.onclick ="alert('Test');";

Jua*_*nez 4 javascript onclick setattribute

比较下列情况时,我感到很惊讶:

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 + "');");
}
Run Code Online (Sandbox Code Playgroud)

只是后者似乎改变了HTML(至少用Firebug进行检查),其余的虽然也正常工作,但他们没有在editBuzonButton元素中显示任何onclick事件.

任何想法为什么会这样?

Rol*_*man 8

是.setAttribute向Element DOM节点添加属性.对于onclick属性,在添加onclick事件处理程序的掩护下存在副作用,该事件处理程序通过将属性值"编译"为javascript函数来实现.

将函数onclick直接分配给元素的属性会附加处理程序,但不会自动将属性添加到DOM节点.

现在有可能是浏览器没有区分添加属性和附加处理程序directy.但请记住,尽管修改文档可能会创建脚本对象作为副作用,但反过来情况并非如此:根据您碰巧使用的浏览器,以编程方式创建DOM结构可能会也可能不会更改文档下的HTML .