前言
有的时候我需要写一个按钮,并且这个按钮在刷新页面的时候记录上次的内容,自动复原,每次都需要这样写一次代码,太过于繁琐了,所以我写了个简单的js库莱解决这个问题。
需要依靠jq执行。
代码
Javascript
const xn = { ls: { get: function (key) { return JSON.parse(localStorage.getItem(key)); }, list: function () { return JSON.parse(localStorage.getItem("")); }, remove: function (key) { localStorage.removeItem(key); }, set: function (key, value) { localStorage.setItem(key, JSON.stringify(value)); } } } const ls = xn.ls; $(document).on("input", "input[af_path]", function () { const element = $(this); value = element.val(); const [fun, tree, ...path] = element.attr("af_path").split(/:|>/).filter(Boolean); if (fun == "ls") { let localStorageTree = ls.get(tree); localStorageTree = localStorageTree ? localStorageTree : {}; let currentObj = localStorageTree; for (let i = 0; i < path.length - 1; i++) { if (!currentObj[path[i]]) { currentObj[path[i]] = {}; } currentObj = currentObj[path[i]]; } currentObj[path[path.length - 1]] = value; ls.set(tree, localStorageTree); } }) $(document).ready(function () { $("input[af_path]").each(function () { const element = $(this); const [fun, tree, ...path] = element.attr("af_path").split(/:|>/).filter(Boolean); if (fun === "ls") { let localStorageTree = ls.get(tree); if (localStorageTree) { localStorageTree = localStorageTree; let targetValue = localStorageTree; for (const pathItem of path) { if (targetValue[pathItem]) { targetValue = targetValue[pathItem]; } else { targetValue = null; break; } } if (targetValue !== null) { element.val(targetValue); } } } }); });
HTML
<input type="text" af_path="ls:tree>1>key>test1"> <input type="text" af_path="ls:tree>2>key>test2"> <input type="text" af_path="ls:tree>2>sdfdsf>test3"> <input type="text" af_path="ls:trsadee123>2>sdfdsf>test3"> <input type="text" af_path="ls:123>2>sdfdsf>test3"> <input type="text" af_path="ls:asd>2>sdfdsf>test3"> <input type="text" af_path="ls:tree>4>key>test4">
Comments NOTHING