使用javascript添加具有现有函数的onclick侦听器 [英] Add an onclick listener with an existing function using javascript

查看:74
本文介绍了使用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);
    }

}



<我推荐d阅读有关quirksmode.org上事件处理的优秀文章

这篇关于使用javascript添加具有现有函数的onclick侦听器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆