js操作cookie完成新增表單,存入cookie及讀取cookie
阿新 • • 發佈:2018-12-20
<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>
原文:https://blog.csdn.net/GengPengShuaiGPS/article/details/77717770