How to pass a parameter to a dynamically set JavaScript function?

In the clickTest function you should have access to a the this variable. Try this inside of clickTest function:

alert(this.id);

This will refer to the DOM element that fired the event.

Basically, there isn't really a way to pass parameters to an event handler function. The reason for that is that the browser is executing the function based on an event and you are not actually calling the function.

You can use closures which allow you to access local variables (to the closure) when you assign the event handler function. That would look like this:

cell.onclick = function() { alert(this.id); alert(cell.id); };

Were cell.id is the locally scoped variable that is still considered in scope when the event handler is executed.


Try this:

cell.onclick = function() { clickTest(rowID); };

The idea is that you are binding the onclick handler to the anonymous function. The anonymous function calls clickTest with rowID as the parameter.

Tags:

Javascript