dynamic event - pass value
-
hi guys. i have loop which needs to attach event on some elements. event must fire function and pass value from within loop. so here is problem... when loop is over all events fire same argument that is passed by ref not value at that time. <a href="#">link 1</a> <a href="#">link 2</a> <a href="#">link 3</a> <script type="text/javascript"> var anchorNiz = document.getElementsByTagName("a"); for(var i=0;i<anchorNiz.length;i++){ var anchor = anchorNiz[i]; anchor.attachEvent("onmouseover",function(){alert(i)}); //this line does same thing, different value //anchor.attachEvent("onmouseover",function(){alert(anchor)}); } //the idea is to set links to fire ordinal number, but all are fireing '3' </script>
-
hi guys. i have loop which needs to attach event on some elements. event must fire function and pass value from within loop. so here is problem... when loop is over all events fire same argument that is passed by ref not value at that time. <a href="#">link 1</a> <a href="#">link 2</a> <a href="#">link 3</a> <script type="text/javascript"> var anchorNiz = document.getElementsByTagName("a"); for(var i=0;i<anchorNiz.length;i++){ var anchor = anchorNiz[i]; anchor.attachEvent("onmouseover",function(){alert(i)}); //this line does same thing, different value //anchor.attachEvent("onmouseover",function(){alert(anchor)}); } //the idea is to set links to fire ordinal number, but all are fireing '3' </script>
you will get 0, 1 and 2
<a href="#">link 1</a>
<a href="#">link 2</a>
<a href="#">link 3</a>
<script type="text/javascript">
var anchorNiz = document.getElementsByTagName("a");
for(var i=0;i<anchorNiz.length;i++){
var anchor = anchorNiz[i];
anchor.attachEvent("onmouseover",(function(){
var arg = arguments[0];
return function(){
alert(arg);}})(i))
}
</script>also attachevent omly works in IE
modified on Tuesday, September 14, 2010 2:24 PM
-
you will get 0, 1 and 2
<a href="#">link 1</a>
<a href="#">link 2</a>
<a href="#">link 3</a>
<script type="text/javascript">
var anchorNiz = document.getElementsByTagName("a");
for(var i=0;i<anchorNiz.length;i++){
var anchor = anchorNiz[i];
anchor.attachEvent("onmouseover",(function(){
var arg = arguments[0];
return function(){
alert(arg);}})(i))
}
</script>also attachevent omly works in IE
modified on Tuesday, September 14, 2010 2:24 PM
thx. very interesting solution....