zoukankan      html  css  js  c++  java
  • localStorage+cookie实现存取表单历史记录

    应用场景:

    1.填入表单内容有不同验证规则,提交表单会进行相应规则验证,通过验证才存;

    2.读取历史记录的时候,根据验证规则筛选,只读取适合相应规则的历史记录数据;

    3.以localStorage存储为主,如果localStorage失效(App中localStorage可能会出现失效场景),则启用cookie存取(这里用了js.cookie.js插件方便操作cookie);

    贴出代码:

    html

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <meta http-equiv="X-UA-Compatible" content="ie=edge">
        <title>Document</title>
        <style>
            *, body{margin: 0;padding:0;}
            .box{ 240px; margin: 100px auto;}
            .username-box{height: 200px;}
            .username{100%; height: 24px;text-indent:12px;border: 1px solid #ccc;border-radius:4px;}
            .submit{ 100%; height:30px;color:#fff;background: #4496e9;border:1px solid #4496e9;border-radius: 4px;}
            .account-label{float: left}
            .account-box{ position: relative; 180px;float: left;}
            .history-account{
                display: none;
                 100%;
                background: #fff;
                border-top:0;
                border-bottom-left-radius: 8px;
                border-bottom-right-radius: 8px;
                position: absolute;
                top:26px;
                left: 0;
                z-index: 9;
                box-shadow: 0px 2px 1px 2px rgba(0,0,0,0.05);
            }
            .history-account>li{
                display: block;
                100%;
                height:30px;
                line-height: 30px;
                text-align: center;
                box-shadow: inset 0px -1px 1px -1px rgba(0,0,0,0.05);
                position: relative;
                cursor:pointer;
            }
            .history-account>li:nth-child(2n+1){background: #f1f1f1}
            .history-account>li:last-child{border-bottom-left-radius: 8px;border-bottom-right-radius: 8px}
            .remove{
                 10px;
                height: 10px;
                position: absolute;
                top: 0px;
                right: 10px;
                cursor: pointer;
            }
            .remove-all{display: block;height:30px;line-height:30px;text-align:center; color: #00A4EA;cursor: pointer}
            .submit-box{clear: both;margin-top:50px;}
            .submit{cursor: pointer}
    
        </style>
    </head>
    <body>
        <div class="box">
            <form>
                <div class="username-box">
                    <label for="username" class="account-label">帐号:</label>
                    <div class="account-box">
                        <input type="text" id="username" class="username" autocomplete="off" />
                    </div>
                </div>
    
                <div class="submit-box">
                    <input type="button" value="确认提交" id="submit" class="submit">
                </div>
            </form>
        </div>
    
        <script type="text/javascript" src="js/jquery-1.12.4.min.js"></script>
        <script type="text/javascript" src="js/js.cookie.js"></script>
        <script type="text/javascript" src="js/index.js"></script>
    </body>
    </html>

    js

    $(function(){
        function historyAccount (type) {
            // 测试localStorage是否能存取到值,能存取就用localStorage,通过isLocal判断
            localStorage.setItem("test",'test');
            var isLocal = localStorage.getItem("test");
    
            // 提交表单按钮,通过验证规则后存入localStorage,Cookie
            $("body").on("click", "#submit", function () {
                // 输入值不为空,才写入历史记录
                if($("#username").val()) {
                    var addArr = [];
                    addArr.push($("#username").val());
                    var newArr = [];
                    // 充值账号验证
                    checkAccount(addArr, type, newArr);
                    if(newArr.length > 0){
                        var newAccount = $("#username").val();
                        var local_data = localStorage.getItem("Account");
                        var cookies_data = Cookies.get("Account");
                        var account = '';
                        if (isLocal) {
                            account = localStorage.getItem("Account");
                        } else {
                            account = Cookies.get("Account");
                        }
                        if (account) {
                            var accounts = account.split(',');
                            var j = 0;
                            for (i = 0, len = accounts.length; i < len; i++) {
                                if (accounts[i] !== $("#username").val()) {
                                    newAccount += "," + accounts[i];
                                    j++;
                                }
                                if(j >= 10) break; // 存储最大条数
                            }
                        }else{
                            localStorage.setItem("Account", JSON.stringify(newArr[0]));
                            Cookies.set('Account', JSON.stringify(newArr[0]));
                        }
                        localStorage.setItem("Account", newAccount);
                        Cookies.set("Account", newAccount);
                    }
                    location.reload();  // 此处刷新是为了模拟提交表单的刷新,更新存储数据,实际项目中可以删除此行代码
                }
            });
    
            // 显示历史充值账号
            function showAccount(){
                var newArr = [];
                var account = '';
                if (isLocal) {
                    account = localStorage.getItem("Account");
                } else{
                    account = Cookies.get("Account");
                }
                var arr = [];
                if(account) {
                    var temple = "";
                    if(account.indexOf(',') < 0) arr.push(account);
                    arr = account.split(',');
                    if(arr.length >= 5){
                        arr = arr.slice(0, 5);  // 历史记录展示最大条数
                    }
                    checkAccount(arr, type, newArr);
                    if(newArr.length > 0) {
                        temple += "<ul class='history-account'>";
                        $.each(newArr, function (i, g) {
                            temple += "<li value="" + i + "">" + g + "<div class='remove'>X</div></li>";
                        });
                        temple +=  "<div class='remove-all'>清除历史</div>";
                        temple += "</ul>";
                    }
                }
                $(".username").after(temple);
            }
            showAccount();
    
            // 移入焦点显示
            $("body").on("click", "#username", function () {
                $(".history-account").show();
            });
    
            // 失去焦点隐藏
            $("body").on("blur", "#username", function () {
                $(".history-account").hide();
            });
    
            // 选中填入表单  blur事件优先于click事件,所以在选中记录的时候,blur先执行了;所以用mousedown(手机端可以用touchstart)事件优先于blur
            $("body").on("mousedown", ".history-account>li:not(.remove-all)", function () {
                $('#username').val($(this).text());
                $(".history-account").hide();
            });
    
            // 清除所有历史记录
            $("body").on("mousedown", ".remove-all", function () {
                alert(1);
                localStorage.removeItem("Account");
                Cookies.remove("Account");
                $('.history-account').remove();
            });
    
            //清除单条历史记录
            $("body").on("mousedown", ".remove", function (event) {
                event.stopPropagation();
                var value = $(this).parent('li').text();
                var local_data = localStorage.getItem("Account");
                var cookies_data = Cookies.get("Account");
                var account = '';
                if (!local_data && cookies_data) {
                    account = Cookies.get("Account");
                } else {
                    account = localStorage.getItem("Account");
                }
                var arr = [];
                console.log('account', account);
                if (account.indexOf(',') >= 0) {
                    arr = account.split(',')
                    if (arr.length >= 5) {
                        arr = arr.slice(0, 5);
                    }
                    Array.prototype.remove = function (val) {
                        for (var i = 0; i < this.length; i++) {
                            if (this[i] == val) this.splice(i, 1);
                        }
                    };
                    arr.remove(value);
                    $(this).parent('li').remove();
                    localStorage.setItem("Account", arr);
                    Cookies.set("Account", arr);
                } else {
                    localStorage.removeItem("Account");
                    Cookies.remove("Account");
                    $('.history-account').remove();
                }
            });
    
            // 根据商品类型筛选账号
            function checkAccount(array, account_type, newArr) {
              var types = account_type.split("|");
              var Reg = '';
              // 验证规则,可以添加修改
              $.each(types, function(i, v) {
                  switch(v){
                      case "":
                      case "0": Reg = ''; break;
                      case "1": Reg = /^(0|86|17951)?(13[0-9]|15[012356789]|17[0-9]|18[0-9]|14[57])[0-9]{8}$/; break;  // 手机
                      case "2": Reg = /^[1-9][0-9]{4,12}$/; break;                                                     // QQ
                      case "3": Reg = /^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(.[a-zA-Z0-9_-]+)+$/; break;                     // 邮箱
                      case "4": Reg = /^(0[0-9]{2,3})-?([0-9]{7,8})$/; break;                                          // 固定电话
                  }
                  // console.log('Reg', Reg);
                  if(array){
                      for (var i = 0, len = array.length; i < len; i++) {
                        if (newArr.indexOf(array[i]) == -1 && array[i].match(Reg)){
                              newArr.push(array[i]);
                          }
                      }
                  }
              });
              console.log('newArr', newArr);
              return  newArr;
           }
        }
        // 传入的参数type字符串类型
        var type = '0';  // "0"||"" -全部  "1"-手机 "2"-QQ "3"-邮箱 "4"-固定电话  "1|2"-手机+QQ "1|2|3"-手机+QQ+邮箱 ...
        historyAccount(type);
    
    })
  • 相关阅读:
    pow()函数结果强制转化为int造成误差的分析
    warning: ISO C++ forbids converting a string constant to 'char*' [-Wwrite-strings]
    博客园鼠标点击特效代码
    codeblocks更改颜色主题
    codeblocks1712设置中文
    SQl
    项目中nodejs包高效升级插件npm-check-updates
    正则表达式的整理(将金钱数变成带有千分位)
    从一个数组中过滤出另外一个数组中相关字段相等的数据
    IONIC3 打包安卓apk详细过程(大量图文)
  • 原文地址:https://www.cnblogs.com/hcxwd/p/7339707.html
Copyright © 2011-2022 走看看