为什么这个textarea没有使用.focus()?

我有这个代码来集中一个textarea当用户点击“回复”button:

$('#reply_msg').live('mousedown', function() { $(this).hide(); $('#reply_holder').show(); $('#reply_message').focus(); }); 

它显示了答复的forms,但textarea不会重点。 我通过AJAX添加textarea,这就是为什么我使用.live() 。 我添加的框显示(我甚#reply_msg通过AJAX添加#reply_msg和东西发生时,我把鼠标放在它),但它不会集中在textarea。


编辑

我的HTML看起来像:

 <div id="reply_msg"> <div class="replybox"> <span>Click here to <span class="link">Reply</span></span> </div> </div> <div id="reply_holder" style="display: none;"> <div id="reply_tab"><img src="images/blank.gif" /> Reply</div> <label class="label" for="reply_subject" style="padding-top: 7px; width: 64px; color: #999; font-weight: bold; font-size: 13px;">Subject</label> <input type="text" id="reply_subject" class="input" style="width: 799px;" value="Re: <?php echo $info['subject']; ?>" /> <br /><br /> <textarea name="reply" id="reply_message" class="input" spellcheck="false"></textarea> <br /> <div id="reply_buttons"> <button type="button" class="button" id="send_reply">Send</button> <button type="button" class="button" id="cancel_reply_msg">Cancel</button> <!--<button type="button" class="button" id="save_draft_reply">Save Draft</button>--> </div> </div> 

点击元素会按以下顺序引发事件:

  1. 鼠标按下
  2. 焦点
  3. 鼠标松开
  4. 点击

所以,这是发生了什么:

  1. mousedown<a>提出
  2. 您手动将<textarea>关注
  3. 默认的事件行为试图将焦点从<textarea>焦点<a>

以下是演示此行为的演示:

 $("a,textarea").on("mousedown mouseup click focus blur", function(e) { console.log("%s: %s", this.tagName, e.type); }) $("a").mousedown(function(e) { $("textarea").focus(); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <a href="javascript:void(0)">reply</a> <textarea></textarea> 

把注意力集中在事件处理程序本身,赋予焦点,总是有问题的。 一般的解决scheme是在超时后设置焦点:

 setTimeout(function() { $('#reply_message').focus(); }, 0); 

这可以让浏览器做它的事情,然后你回来,把注意力集中到你想要的地方。

难道这是同样的问题? jQuery的Textarea的重点

尝试在.show()完成后调用.focus()

 $('#reply_msg').live('mousedown', function() { $(this).hide(); $('#reply_holder').show("fast", function(){ $('#reply_message').focus(); }); }); 

我今天遇到了这个问题,在我的情况下,这是由于jQuery UI(v1.11.4)中的一个错误,导致textarea元素内的draggable / droppable元素停止默认点击行为textarea收到焦点之前。

解决scheme是重新制作用户界面,以便textarea不再出现在可拖动元素内部。

这是一个特别困难的问题debugging,所以我在这里留下一个答案,以防其他人觉得有用。