【问题标题】:get localStorage value automatically when a tab is open or activated打开或激活选项卡时自动获取 localStorage 值
【发布时间】:2017-09-28 12:50:25
【问题描述】:

我需要在tags.php 上设置一个localStorage 项,并在用户切换到index.php 时自动获取其更新值。

tags.php

$(document).on('click', '.tagdown', function() {
    var a = $('#tagsup').html();
    localStorage.setItem('tags', a);
});

index.php
这里我需要这样的东西:

$(window).onfocus(function(){
console.log(localStorage.getItem('tags'));
});

$(window).onfocus() - 不存在。

如果 body-child 元素有焦点,我尝试使用 body.onfocus 不起作用。

任何帮助。

【问题讨论】:

标签: javascript window focus


【解决方案1】:

您可以为此使用focus() 事件:

$(function() {
    $(window).focus(function() {
        console.log('Window is in focus');
        console.log(localStorage.getItem('tags'));
    });
});

【讨论】:

    【解决方案2】:

    应该是focus 而不是onfocus

    $(window).focus(function(){
        console.log(localStorage.getItem('tags'));
    });
    

    【讨论】:

      【解决方案3】:

      您也可以使用on 并专注于窗口,而不是onfocus。 on 也适用于动态创建的元素。

      jQuery(window).on('focus',  function(e){
              console.log("focused on " + $(e.target));
      });
      <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
      
      Click anywhere in the window

      【讨论】:

        猜你喜欢
        • 2022-08-10
        • 2017-08-08
        • 2017-04-19
        • 2014-10-09
        • 1970-01-01
        • 2012-01-04
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多