js操作cookie完成添加表单,存入cookie及读取cookie

来源:互联网 发布:linux ant是否安装 编辑:程序博客网 时间:2024/06/03 07:10
<script type="text/javascript">
        function saveData(){
            var d = new Date();
              d.setTime(d.getTime() + 2*60*60*1000);
              var expires = ";expires="+d.toUTCString();
            //获取所有的input
            $("input").each(function(){
                var id = $(this).attr('id');
                var val = $.trim($(this).val());
                document.cookie = id + '=' + val + expires;
            })
            //获取所有的select
            $("select").each(function(){
                var id = $(this).attr('id');
                var val = $.trim($(this).val());
                document.cookie = id + '=' + val + expires;
            })
            //获取所有的textarea
            $("textarea").each(function(){
                var id = $(this).attr('id');
                var val = $.trim($(this).val());
                document.cookie = id + '=' + val + expires;
            })
            //图片
            $("img").each(function(){
                var id = $(this).attr('id');
                var val = $.trim($(this).attr("src"));
                document.cookie = id + '=' + val + expires;
            })
        }
        function loadData(){
            var cookie = document.cookie;
            cookie += ";";
            //给获取所有的input赋值
            $("input").each(function(){
                var id = $(this).attr('id');
                $(this).val(getValue(id,cookie));
            })
            //给获取所有的select赋值
            $("select").each(function(){
                var id = $(this).attr('id');
                $(this).val(getValue(id,cookie));
            })
            //给获取所有的textarea赋值
            $("textarea").each(function(){
                var id = $(this).attr('id');
                $(this).val(getValue(id,cookie));
            })
            //图片
            $("img").each(function(){
                var id = $(this).attr('id');
                $(this).attr("src",getValue(id,cookie));
            })
        }
        function getValue(id,cookie){
            var cookie_pos = cookie.indexOf(id);
            if(cookie_pos != '-1'){
                cookie_pos += id.length + 1;

                var cookie_end = cookie.indexOf(";", cookie_pos);

               if(cookie_end == '-1'){

                     cookie_end = cookie.length;

               }

                var value  = cookie.substring(cookie_pos, cookie_end);
                return value;
            }
        }
    </script>
原创粉丝点击