attaching event to element in IE via JS and passing in the object itself
I have this bit of JS that is called as it loops through each of the INPUT elements on the page:
if (thisField.addEventListener){ // good browsers
thisField.addEventListener('focus', function(event){toggleHelpText(this,event)}, true);
thisField.addEventListener('blur', function(event){toggleHelpText(this,event)}, false);
} else if (thisField.attachEvent){ // IE
thisField.attachEvent('onfocus',function(event){toggleHelpText(thisField,event)});
thisField.attachEvent('onblur',function(event){toggleHelpText(thisField,event)});
}
In good browsers, it does what it's supposed to do. It attaches a focus and blur event listener to each element that, when triggered, passes in the object and the event that triggered it to the function 'toggleHelpText'.
IE doesn't work, though. What happens in IE is that every field that has the event listener attached to it has the object 'thisField' referring to only the last object in the loop.
In otherwords, if I have 3 input fields, the good browser will call a focus event on each one passing field1, field2, and field3 as 'this' respectively.
In IE, all 3 fields, when triggering the focus event, pass field3 as an object.
Is there a solution?
I also tried the following syntax options only to get errors in IE:
thisField.attachEvent('onblur',function(event){toggleHelpText(this,event)});
thisField.attachEvent('onblur',function(this,event){toggleHelpText(thisField,event)});
thisField.attachEvent('onblur',function(this,开发者_StackOverflow社区event){toggleHelpText(this,event)});
Hey, In IE , the event handlers are not provided the fired event as argument. you have to collect it by window.event.
Solution:
This was my original logic:
for loop...
attach events to each item passing object[i]
That worked fine except for IE, where the same obj was being passed to each event listener (the last object in the array).
The fix is to do this:
for loop...
call function to attach events passing object[i]
function
attach events to each item passing object[i]
I've run into this before...this is a closure issue, correct?
精彩评论