简体   繁体   中英

Can't set focus() on a text field

This is just the weirdest thing. I've got a Sammy.js app, and I want to set focus on a text field right after the HTML loads. I've got this CoffeeScript here:

this.partial('templates/my-template.jqt').then ->
  i = $('#item')
  debugger
  i.focus()

While I'm in the debugger, right on that line, I can inspect "i" and see that it's a JQuery object. I can even call i.val("HI THERE!") and see my text field update. But, calling i.focus() does absolutely nothing. Is there some security feature I'm missing that doesn't let you focus on a text element that was dynamically loaded?

Try:

setTimeout(function() { $('#item').focus() }, 1);

It's quite common issue. For some reason delaying the focus for 1ms makes it working.

JQuery's focus() doesn't focus on an element, it binds an event handler to focus. http://api.jquery.com/focus/

Try i.get().focus() instead.

像这样做:

i.trigger 'focus'

If you are sure that you are getting $('#item') object.You can try out few things.

Make sure that you have only one input box with <input type="text" id="item" /> .Same id should not be repeated.

Next thing is why dont you try $('#item').focus() .

Thanks. with regards,

Wasim

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM