检索以前关注的元素

Mic*_*ick 6 javascript

我想在Javascript中找出哪个前一个元素具有焦点而不是当前焦点.我一直在浏览DOM,但还没找到我需要的东西.有没有办法做到这一点任何帮助将不胜感激

Pet*_*tai 9

每次元素聚焦时,您都必须存储它是哪一个.然后当另一个元素被聚焦时,您可以检索前一个聚焦元素的变量.

所以基本上,你的焦点处理程序会做两件事:

  1. 检查是否定义了previousFocus.如果是,请检索它.
  2. 将previousFocus设置为当前聚焦的元素.

这是一个使用jQuery的快速演示(你也可以使用原始的JS ...只需更少的行jQuery,所以它更容易理解imo):

  // create an anonymous function that we call immediately
  // this will hold our previous focus variable, so we don't
  // clutter the global scope
(function() {

      // the variable to hold the previously focused element
    var prevFocus;

      // our single focus event handler
    $("input").focus(function() {

          // let's check if the previous focus has already been defined
        if (typeof prevFocus  !== "undefined") {

              // we do something with the previously focused element
            $("#prev").html(prevFocus.val());
        }

          // AFTER we check upon the previously focused element
          //   we (re)define the previously focused element
          //   for use in the next focus event
        prevFocus = $(this);
    });
})();
Run Code Online (Sandbox Code Playgroud)

工作jsFiddle


Gon*_*ing 8

刚刚解决完全相同的问题时发现了这个问题,并意识到它已经很久了jQuery世界已经移动了一点:)

这应该提供更有效的Peter Ajtais代码版本,因为它只使用一个委托事件处理程序(每个输入元素不是一个).

// prime with empty jQuery object
window.prevFocus = $();

// Catch any bubbling focusin events (focus does not bubble)
$(document).on('focusin', ':input', function () {

    // Test: Show the previous value/text so we know it works!
    $("#prev").html(prevFocus.val() || prevFocus.text());

    // Save the previously clicked value for later
    window.prevFocus = $(this);
});
Run Code Online (Sandbox Code Playgroud)

JSFiddle: http ://jsfiddle.net/TrueBlueAussie/EzPfK/80/

笔记:

  • 使用$()创建一个空的jQuery对象(允许它立即使用).
  • 由于这个使用jQuery :input选择器,它使用select&button元素和输入.
  • 它不需要document始终存在的DOM就绪处理程序.
  • 由于需要先前关注的控件,"elsehere"被简单地存储在window全球使用中,因此它不需要IIFE函数包装器.