IE attachEvent call returns true, but handler shows “null”

会有一股神秘感。 提交于 2019-12-24 14:09:34

问题


I have a fairly simple ASP.NET page that renders an HTML input (text box). Within the generated HTML, I attach a handler to several events, including onfocus, onkeypress, and onkeyup. Because this is a solution targeted at a version of IE that does not support addEventListener (situation about which I can do nothing), I am forced to use attachEvent.

A typical call to attachEvent is as follows - I've excerpted this source from the original for the sake of brevity/clarity, so it is not precisely the code at issue:

var hostControl = document.getElementById('mytextbox');
var attachResult = hostControl.attachEvent('onfocus', function(){
    hostControl.select();
});

if (!attachResult)
{
    alert('Attach failed.');
}

attachResult = hostControl.attachEvent('onblur', function(){
    if (hostControl.value=='') 
    {
        alert('Warning - no entry.');
    }
});

if (!attachResult)
{
    alert('Attach failed.');
}

When I step through this code in the IE debugger, attachEvent returns 'true' in both instances, which should indicate that the event attachment attempt was successful. However, when I look at the [Event] handlers for the control within the debugger, all the events show 'null', no handler attached.

Things I've tried/researched:

  • I've read several different articles on the vagaries of event attachment in IE, so I've speciously avoided any 'this' references.
  • I tried one version that used one of the addEvent wrapper blocks that tries to use addEventListener if available, even though I knew this would be an IE solution.

When I tried that version against FireFox, event attachment worked properly through addEventListener, but failed in IE using attachEvent (with attachEvent still returning true).

  • I then opted to eliminate any possible problems the wrapper might be introducing, and used attachEvent directly against the control, which leads me where I am now. The problem persists.

I would like to think I've simply overlooked something very simple, as I've hooked up events before without difficulty, but something here is throwing me a curveball I just don't recognize. Appreciate the extra eyeballs on this to see where I've erred.

来源:https://stackoverflow.com/questions/15952943/ie-attachevent-call-returns-true-but-handler-shows-null

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!