Add an onclick listener with an existing function using javascript

前端 未结 1 1400
深忆病人
深忆病人 2021-01-24 09:57

I have an existing javascript function:

function changeColor(ID){

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

}


        
相关标签:
1条回答
  • 2021-01-24 10:18

    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).

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

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

    where changeColor is defined as

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

    I recommend to read the excellent articles about event handling on quirksmode.org.

    0 讨论(0)
提交回复
热议问题