JS: dynamic onclick event handler creation troubles...
Posted: Sun Aug 12, 2007 3:52 pm
feyd | Please use
What I'm trying to do here is iterate through all buttons in the dom and add an event handler w/ a unique argument. The argument is built based on the index of the button.
The problem is javascript stores a reference to that argument instead of a value. So all onclick event handlers have their arguments pointing to the last argument generated...in the case of this example, 'arg_2'.
Anyone know of a solution to this problem? I'm looking for the simplest "cross bowser support" solution. What is the standard convention for dynamically creating event handlers?
One solution I have thought of is to assign the index of the button to it's id. Then in the event handler's function argument is just "this.id". Is this a hack? And what happens if I want multiple arguments? Do i begin assigning these arguments to the buttons' other attributes (ie. name, class, etc...). This is looking more and more like a hack.
Thanks.
feyd | Please use[/syntax]
Code: Select all
,Code: Select all
and [syntax="..."] tags where appropriate when posting code. Your post has been edited to reflect how we'd like it posted. Please read: [url=http://forums.devnetwork.net/viewtopic.php?t=21171]Posting Code in the Forums[/url] to learn how to do it too.[/color]
Hey All,
I'm having problems creating onclick event handlers by editing the dom in javascript.
Sample pseudo code:
[syntax="html"]
//DOM:
<div id='containerDiv>
<input type='button' />
<input type='button' />
<input type='button' />
</div>
//js code:
var l_div = $('containerDiv');
for( var i=0; i<3; i++ )
{
var l_inputButton = l_div.getChildElements()[i];
var l_arg = "arg_" + i;
l_inputButton.onclick = function() { some_js_function( l_arg ); };
}
The problem is javascript stores a reference to that argument instead of a value. So all onclick event handlers have their arguments pointing to the last argument generated...in the case of this example, 'arg_2'.
Anyone know of a solution to this problem? I'm looking for the simplest "cross bowser support" solution. What is the standard convention for dynamically creating event handlers?
One solution I have thought of is to assign the index of the button to it's id. Then in the event handler's function argument is just "this.id". Is this a hack? And what happens if I want multiple arguments? Do i begin assigning these arguments to the buttons' other attributes (ie. name, class, etc...). This is looking more and more like a hack.
Thanks.
feyd | Please use[/syntax]
Code: Select all
,Code: Select all
and [syntax="..."] tags where appropriate when posting code. Your post has been edited to reflect how we'd like it posted. Please read: [url=http://forums.devnetwork.net/viewtopic.php?t=21171]Posting Code in the Forums[/url] to learn how to do it too.[/color]