【问题标题】:I want a JQuery code that sets the focus to the previous selected input我想要一个 JQuery 代码,将焦点设置为上一个选定的输入
【发布时间】:2017-01-09 10:41:48
【问题描述】:

例子:

<input type=text id="fText">
<input type=text id="sText">
<input type=text id="tText">
<input type=button id="rest">

当我点击 fText 然后按下按钮时,光标返回到 fText 当我单击 sText 然后按下按钮时,光标返回到 sText 等等..

【问题讨论】:

  • 将输入存储在输入的模糊事件处理程序中,并将焦点设置到按钮单击处理程序中存储的元素。
  • 这里不是订购代码的地方。

标签: javascript jquery


【解决方案1】:

只需将最后一个获得焦点的输入元素保存到一个全局变量中,然后在单击按钮时对其进行聚焦。

var lastFocus;

$("input[type=text]")
  .on("focus", function () {
    lastFocus = this;
});

$("#rest")
  .click(function () {
    if (lastFocus) {
      $(lastFocus).focus();
    }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type=text id="fText">
<input type=text id="sText">
<input type=text id="tText">
<input type=button id="rest">

【讨论】:

  • 谢谢,我刚接触 JQuery 编程
  • 不确定为什么您会因此而受到反对,这是对所提出问题的合法解决方案。仅仅因为 OP“有序代码”并不意味着发布一些内容的人应该被否决。只需标记问题并继续。
  • @Christoph,我打算否决这个问题。看来我错误地对你投了反对票。除非您编辑答案,否则我无法删除它。请进行一些修改
  • 啊,没关系。无需进行不必要的编辑 :) 但是 Amer Huriz 可以很好地将答案标记为已接受的答案。
猜你喜欢
  • 1970-01-01
  • 2010-11-16
  • 1970-01-01
  • 1970-01-01
  • 2016-10-22
  • 2015-06-25
  • 1970-01-01
  • 2017-02-10
  • 1970-01-01
相关资源
最近更新 更多