使用javascript添加具有现有函数的onclick侦听器

使用javascript添加具有现有函数的onclick侦听器

问题描述:

我有一个现有的javascript函数:

I have an existing javascript function:

function changeColor(ID){

    try{
        initialize();
    }
    finally{
        changeDesign(ID);
    }

}

我想做这样的事情:

for(var x=0; x<2; x++){
        document.getElementById(x).onclick = "changeColor(" + x +")";
}

html的输出应为:

The output with the html should be:

<tr bgcolor="#FFFFFF" id="0" onclick="changeColor(0)>


通过DOM API分配事件处理程序修改实际的HTML(实际上,浏览器收到的HTML源代码是只读的。

Assigning an event handler via the DOM API does not modify the actual HTML (in fact, the HTML source that the browser receives is readonly).

您必须将函数分配给。 onclick ,而不是字符串:

You have to assign a function to .onclick, not a string:

for(var x=0; x<2; x++){
    document.getElementById(x).onclick = changeColor;
}

其中 changeColor 定义为

function changeColor(){
    var ID = this.id; // `this` refers to element the handler is bound to

    try{
        initialize();
    }
    finally{
        changeDesign(ID);
    }

}



有关quirksmode.org上事件处理的优秀文章。