检索以前关注的元素 [英] Retrieving previously focused element

查看:87
本文介绍了检索以前关注的元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I would like to find out, in Javascript, which previous element had focus as opposed to the current focus. I've been looking through the DOM and haven't found what I need, yet. Is there a way to do this any help would be much appreciated

推荐答案

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

Each time an element is focused, you'd have to store which one it was. Then when another element is focused, you could retrieve the variable for the previous focused element.

所以基本上,你的单个焦点处理程序会做 2件事

So basically, your single focus handler would do 2 things:


  1. 检查是否定义了previousFocus。如果是,请检索它。

  2. 将previousFocus设置为当前关注的元素。

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

Here is a quick demo with jQuery (you can use raw JS too... just fewer lines w jQuery, so it's easier to understand 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);
    });
})();

这篇关于检索以前关注的元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆