首页 > 解决方案 > 使用“localStorage.setItem”Internet Explorer

问题描述

我想localStorage.setItem在 Internet Explorer 11 中使用,

我试过像:

<script>
  localStorage.setItem("lastname", "Smith");
</script>

但在 IE 控制台中我看到:

SCRIPT5007:无法获取未定义或空引用的属性“setItem”。

我还尝试了给定的答案,例如:

<script>
!localStorage && (l = location, p = l.pathname.replace(/(^..)(:)/, "$1$$"), (l.href = l.protocol + "//127.0.0.1" + p));

if (typeof(Storage) != "undefined") {
    // Store
    localStorage.setItem("lastname", "Smith");
    // Retrieve
    alert(localStorage.getItem("lastname"));
} else {
    alert("Sorry, your browser does not support Web Storage...");
}
</script>

但后来我得到:

在此处输入图像描述

标签: javascriptlocal-storageinternet-explorer-11

解决方案


  • 请在 IE 11 中勾选此选项,如果禁用此选项,存储对象将在 IE 中未定义:
    1. 单击“工具”菜单并选择“Internet 选项”。
    2. 单击标有“高级”的选项卡。
    3. 选中“启用 DOM 存储”复选框。
    4. 单击“应用”,单击“确定”。

在此处输入图像描述

  • localstorage无法使用file://协议,您需要通过 http 协议运行页面。
  • win7/win8的旧版IE 11可能存在问题,请确保您已安装最新更新。localstorage

推荐阅读