开发者

How to cancel onblur event of a control in JavaScript?

I am transf开发者_如何学编程erring the focus to a control on onblur event of a dropdown, the focus is transferred to the desired control and also the onblur event written for that control is getting executed which I don't want. How do I prevent this from happening?


If you set the focus while focus is already being set, you can expect all kinds of odd events to fire. The issue isn't specific to Javascript; it happens on every GUI I've ever worked with. You can't reliably stop the events from firing, and you probably won't get the same ones in the same order if you try a different browser or run on a different OS.

I've always used a boolean variable as a flag to note whether I'm in the middle of setting the focus myself, and quietly return from onblur() and the like when that flag is set. Something like

var isFocusGettingMessedWith;
...
isFocusGettingMessedWith = true;
someControl.focus();
isFocusGettingMessedWith = false;
...
function someControl_onblur(event) {
    if (!isFocusGettingMessedWith) { /* do something */ }
}
function otherControl_onblur(event) {
    if (!isFocusGettingMessedWith) { /* do something */ }
}

This approach has worked reliably on every language/platform combination where I've had cause to use it.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜