window.name存储javascript数据靠谱么
高洛峰
高洛峰 2017-04-10 17:28:32
[JavaScript讨论组]

由于window.name没有兼容性问题,基于同一个窗口共享数据,所以想实现在同一个窗口加载不同页面使它们共享数据,就想到用window.name,请问这样使用window.name靠谱么???

高洛峰
高洛峰

拥有18年软件开发和IT教学经验。曾任多家上市公司技术总监、架构师、项目经理、高级软件工程师等职务。 网络人气名人讲师,...

全部回复(1)
巴扎黑

用localStorage吧,有兼容IE低版本的方案。

    "use strict";
    //localStorage support ie6-8
    if(typeof window.localStorage === 'undefined'){

        var localStorage = window.localStorage = {},
            prefix = 'data-userdata',
            doc = document,
            attrSrc = doc.body,
            html = doc.documentElement,

        // save attributeNames to <html>'s
        // data-userdata attribute
            mark = function (key, isRemove, temp, reg) {

                html.load(prefix);
                temp = html.getAttribute(prefix);
                reg = new RegExp('\\b' + key + '\\b,?', 'i');

                var hasKey = reg.test(temp) ? 1 : 0;

                temp = isRemove ? temp.replace(reg, '').replace(',', '') :
                    hasKey ? temp : temp === '' ? key :
                        temp.split(',').concat(key).join(',');


                html.setAttribute(prefix, temp);
                html.save(prefix);

            };

        // add IE behavior support
        attrSrc.addBehavior('#default#userData');
        html.addBehavior('#default#userData');

        localStorage.getItem = function (key) {
            attrSrc.load(key);
            return attrSrc.getAttribute(key);
        };

        localStorage.setItem = function (key, value) {
            attrSrc.setAttribute(key, value);
            attrSrc.save(key);
            mark(key);
        };

        localStorage.removeItem = function (key) {
            attrSrc.removeAttribute(key);
            attrSrc.save(key);
            mark(key, 1);
        };

        // clear all attributes on <body> that using for textStorage
        // and clearing them from the 'data-userdata' attribute's value of <html>
        localStorage.clear = function () {

            html.load(prefix);

            var attrs = html.getAttribute(prefix).split(','),
                len = attrs.length;

            for (var i = 0; i < len; i++) {
                attrSrc.removeAttribute(attrs[i]);
                attrSrc.save(attrs[i]);
            }

            html.setAttribute(prefix, '');
            html.save(prefix);

        };
    }

IE低版本用userData存储。(代码来自网络)

热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 意见反馈 讲师合作 广告合作 最新更新 English
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习
PHP中文网抖音号
发现有趣的

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号