最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Is it possible to focus the same textbox on it's onBlur() event? - Stack Overflow

programmeradmin1浏览0评论

I have HTML:

<input type="text" id="text1" onBlur="focusMe(this.id);" />

and javascript function:

function focusMe(Id)
{
document.getElementById(Id).focus();
}

I have HTML:

<input type="text" id="text1" onBlur="focusMe(this.id);" />

and javascript function:

function focusMe(Id)
{
document.getElementById(Id).focus();
}
Share Improve this question edited Jul 13, 2010 at 1:42 Ned Batchelder 377k77 gold badges581 silver badges673 bronze badges asked Jan 5, 2010 at 13:24 VikasVikas 24.4k37 gold badges119 silver badges159 bronze badges 2
  • @nickf - Did you see the title of the question? – Oded Commented Jan 5, 2010 at 13:28
  • 1 Yeah I saw it, but there's code which has been written and we're being asked if it works? Just run it and find out, geez! – nickf Commented Jan 5, 2010 at 13:31
Add a ment  | 

3 Answers 3

Reset to default 7

It is possible:

function focusMe(Id) {
    setTimeout(function() {document.getElementById(Id).focus();}, 0);
}

Your script is not working because onBlur is called just before the focus is lost.

Two remarks:

  • you'd better use a reference to the input rather than its id
  • why do this?!

I would just pass the control directly. Why pass the ID just to get the control back from it again?

Markup:

<input type="text" id="text1" onBlur="focusMe(this);" />

Javascript:

function focusMe(elem)
{
  elem.focus();
}

Well, running your code shows that it doesn't work, and probably with very good reason.

Since I'm here, I should point out that you can actually pass a reference to this rather than this.id and save some hassle:

onBlur="focusMe(this)"

function focusMe(el) {
    el.focus();
}

But it doesn't work anyway, so it's a tad moot.

发布评论

评论列表(0)

  1. 暂无评论