将表单值保存到localstorage

发布于 2025-01-27 10:10:05 字数 2728 浏览 3 评论 0原文

我已经研究JS了一段时间,所以在某个时候,A无法完成我的老师给我的作业,因此它将创建一个输入以填充3个选择器以更改文本的某些属性。

我要做的是:
每当用户关闭页面并再次打开页面时 - 将localstorage中的值应用于表单中,并将样式应用于元素。 IE:

字体:roboto
颜色:绿色
fontsize:24px

我应该怎么做,为什么我的代码错了?
这是代码:

function iterator() {
  for (let i = 16; i <= 30; i++) {
    let fontsSize = document.getElementById("fontsSize");
    let CreateElmt = document.createElement("option");
    fontsSize.append(CreateElmt);
    CreateElmt.textContent = i + "px";
    CreateElmt.value = i + "px";
  }
}
iterator();

function finalItreator() {
  let parent = document.querySelector(".daddyDiv");
  let div = document.querySelector(".paragragh");
  let Fonts = document.getElementById("Fonts");
  let Colors = document.getElementById("Colors");
  let fontSizes = document.getElementById("fontsSize");
  parent.addEventListener("input", (e) => {
    window.localStorage.setItem("Font", Fonts.value);
    window.localStorage.setItem("Color", Colors.value);
    window.localStorage.setItem("FontSize", fontSizes.value);
    div.style.fontFamily = Fonts.value;
    div.style.color = Colors.value;
    div.style.fontSize = fontSizes.value;
    for (i = 0; i < Fonts.children.length; i++) {
      if (Fonts.children[i].value === window.localStorage.getItem("Font")) {
        Fonts.forEach((e) => {
          e.removeAttribute("selected");
        });
        Fonts.children[i].classList.add("active");
      }
      if (Fonts.children[i].classList.contains("active")) {
        Fonts.children[i].setAttribute("selected", "");
      }
    }
  });
}
finalItreator();
.paragragh {
  margin: 10px auto;
  width: 400px;
  min-height: 300px;
  background-color: #ddd;
  text-align: center;
  padding-top: 30px;
}
<form class="daddyDiv">
  <select name="Fonts" id="Fonts">
    <option value="Open Sans">Open Sans</option>
    <option value="Cairo">Cairo</option>
    <option value="Roboto">Roboto</option>
  </select>
  <select name="Colors" id="Colors">
    <option value="Black">Black</option>
    <option value="Green">Green</option>
    <option value="Blue">Blue</option>
    <option value="Red">Red</option>
    <option value="Purple">Purple</option>
  </select>
  <select name="fontsSize" id="fontsSize"></select>
  <div class="paragragh" contenteditable="true"></div>
</form>

I have been studying JS for a while so at some point a couldn't complete the assignment that my teacher gave me so its all about to create a input to fill with 3 selectors to change some properties of the text.

What I'm trying to do is:
whenever the user he closes the page and opens it again - apply the values from localStorage back into the form, and apply the styles to an element. I.e:

Font: Roboto
Color: Green
fontSize: 24px

How I am supposed to do it, and why my code is wrong?
Here's the code :

function iterator() {
  for (let i = 16; i <= 30; i++) {
    let fontsSize = document.getElementById("fontsSize");
    let CreateElmt = document.createElement("option");
    fontsSize.append(CreateElmt);
    CreateElmt.textContent = i + "px";
    CreateElmt.value = i + "px";
  }
}
iterator();

function finalItreator() {
  let parent = document.querySelector(".daddyDiv");
  let div = document.querySelector(".paragragh");
  let Fonts = document.getElementById("Fonts");
  let Colors = document.getElementById("Colors");
  let fontSizes = document.getElementById("fontsSize");
  parent.addEventListener("input", (e) => {
    window.localStorage.setItem("Font", Fonts.value);
    window.localStorage.setItem("Color", Colors.value);
    window.localStorage.setItem("FontSize", fontSizes.value);
    div.style.fontFamily = Fonts.value;
    div.style.color = Colors.value;
    div.style.fontSize = fontSizes.value;
    for (i = 0; i < Fonts.children.length; i++) {
      if (Fonts.children[i].value === window.localStorage.getItem("Font")) {
        Fonts.forEach((e) => {
          e.removeAttribute("selected");
        });
        Fonts.children[i].classList.add("active");
      }
      if (Fonts.children[i].classList.contains("active")) {
        Fonts.children[i].setAttribute("selected", "");
      }
    }
  });
}
finalItreator();
.paragragh {
  margin: 10px auto;
  width: 400px;
  min-height: 300px;
  background-color: #ddd;
  text-align: center;
  padding-top: 30px;
}
<form class="daddyDiv">
  <select name="Fonts" id="Fonts">
    <option value="Open Sans">Open Sans</option>
    <option value="Cairo">Cairo</option>
    <option value="Roboto">Roboto</option>
  </select>
  <select name="Colors" id="Colors">
    <option value="Black">Black</option>
    <option value="Green">Green</option>
    <option value="Blue">Blue</option>
    <option value="Red">Red</option>
    <option value="Purple">Purple</option>
  </select>
  <select name="fontsSize" id="fontsSize"></select>
  <div class="paragragh" contenteditable="true"></div>
</form>

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

听不够的曲调 2025-02-03 10:10:05
  • 无需一次又一次地查询循环中的DOM。
    缓存元素您计划事先重复使用。
  • 使用const 当变量值不会通过应用程序的寿命变化时
  • ,您的意思是“ paragragh” ? (顺便说一句,它是 div
  • 无需使用id,如果您已经使用name name
  • 不命名function 迭代器 如果其作业显然是用&lt; option&gt; s填充选择框。 CreateFontSizeOptions似乎是一个更好的选择。
  • 不要命名函数 finalItreator 这没什么意思。
    将您的功能名称描述为简洁,有意义且尽可能短。
  • (实际上,您根本不需要这些功能)
  • 不要命名ID的Pascalcase。使用骆驼。
  • “输入”事件分配给类选择器,即:.command,该分配给您的选择(或其他纯)元素。
  • 使用适当的name哪个值完全是预期的CSS属性,即骆驼,即:fontfamilyfontsize
  • 将使用<存储到localStorage中,使用< a href =“ https://developer.mozilla.org/en-us/docs/web/javascript/reference/reference/global_objects/json/json/stringify” rel =“ nofollow noreferrer
  • ” ,将字符串从localstorage中获取为对象,第二个将对象保存到localStorage的对象,而第三个将键/值对样式应用于所需的元素,使用 object.sign.assign
  • 创建一些可重复使用的DOM实用程序,以帮助您获得或创建DOM中的元素

(由于出于安全原因堆栈溢出摘要不接受iframe访问localstorage的访问,因此这里是 /a>

代码:

// DOM utility functions:

const el = (sel, par) => (par || document).querySelector(sel);
const els = (sel, par) => (par || document).querySelectorAll(sel);
const elNew = (tag, prop) => Object.assign(document.createElement(tag), prop);


// TASK:

// Cache DOM Elements:
const elForm = el("#formSettings"); // It's not a ".daddyDiv"... it's a Form!
const elEditable = el("#editable"); // It's an editable div! (What means "paragragh" anyways?!)
const elsCommand = els(".command"); // All your input/selects
const elFontSize = el("[name=fontSize]");

// Create the font-size Options
// (You don't need a function here if it's a one-time operation on DOM ready)
for (let i = 16; i <= 30; i++) {
  elFontSize.append(elNew("option", {
    textContent: `${i}px`,
    value: `${i}px`
  }));
}

const commandsGet = () => {
  // If we have no commands stored in localStorage, save them!
  if (!localStorage.commands) commandsSave();
  // Convert string from localStorage to Object Literal
  const commands = JSON.parse(localStorage.commands);
  // Apply values to DOM input/select elements by name
  Object.entries(commands).forEach(([name, value]) => {
    el(`[name="${name}"]`).value = value;
  });
};

const commandsSave = () => {
  // Create an Object of the commands to save to localStorage
  const commands = [...elsCommand].reduce((obj, elem) => {
    obj[elem.name] = elem.value;
    return obj;
  }, {});
  // Convert object Literal to String and save to localStorage
  localStorage.commands = JSON.stringify(commands);
};

const commandsApply = () => {
  // Apply styles to the desired contenteditable element:
  Object.assign(elEditable.style, JSON.parse(localStorage.commands));
};

// Assign an event listener to all your inputs/selects to store and apply the 
// styles (commands) on "input"
elsCommand.forEach(elem => {
  elem.addEventListener("input", () => {
    commandsSave();
    commandsApply();
  });
});

// Init:
// On page load read the commands from LocalStorage
// and apply them to your editable element
commandsGet();
commandsApply();
/*QuickReset */

* {
  margin: 0;
  box-sizing: border-box;
}

.paragragh {
  margin: 10px auto;
  min-width: 400px;
  min-height: 300px;
  background-color: #ddd;
  text-align: center;
  padding-top: 30px;
}
<form id="formSettings">
  <select class="command" name="fontFamily">
    <option value="Arial">Arial</option>
    <option value="Times New Roman">Times New Roman</option>
    <option value="Courier New">Courier New</option>
  </select>
  <select class="command" name="color">
    <option value="black">Black</option>
    <option value="green">Green</option>
    <option value="blue">Blue</option>
    <option value="red">Red</option>
    <option value="purple">Purple</option>
  </select>
  <select class="command" name="fontSize"></select>

  <div id="editable" contenteditable="true">Lorem ipsum dolor sit amet consectetur adipisicing elit.</div>
</form>
  • There's no need to query the DOM inside a for loop for the same element again and again.
    Cache the elements you plan to reuse beforehand.
  • Use const when the variable value will not change through the life of your app
  • What means "paragragh" you mean paragraph? (BTW, it's a DIV)
  • There's no need to use id if you already use name
  • Don't name a function iterator if its job is clearly to populate a Select box with <option>s. createFontSizeOptions seems like a better choice.
  • Don't name a function finalItreator it means nothing.
    Describe your function names as concisely, meaningfully, and short as possible.
  • (Actually, you don't need those functions at all)
  • Don't name your ID's PascalCase. Use camelCase.
  • Assign the "input" Event to a class selector, i.e: .command which is assigned to your Select (or other imput) elements.
  • Use a proper name which value is exactly the expected CSS property as camelCase, i.e: fontFamily or fontSize
  • Store into LocalStorage a Stringified Object literal using JSON.stringify
  • Retrieve from localStorage using JSON.parse
  • Create three functions, one that gets the String as Object from localStorage, the second to save an Object to localStorage, and a third one to apply the key/value pairs styles to a desired element using Object.assign
  • Create some reusable DOM utilities to help you with getting or creating elements in the DOM

(Since Stack Overflow Snippets for security reasons doesn't accept access to localStorage from Iframe, here's a live jsFiddle demo)

Code:

// DOM utility functions:

const el = (sel, par) => (par || document).querySelector(sel);
const els = (sel, par) => (par || document).querySelectorAll(sel);
const elNew = (tag, prop) => Object.assign(document.createElement(tag), prop);


// TASK:

// Cache DOM Elements:
const elForm = el("#formSettings"); // It's not a ".daddyDiv"... it's a Form!
const elEditable = el("#editable"); // It's an editable div! (What means "paragragh" anyways?!)
const elsCommand = els(".command"); // All your input/selects
const elFontSize = el("[name=fontSize]");

// Create the font-size Options
// (You don't need a function here if it's a one-time operation on DOM ready)
for (let i = 16; i <= 30; i++) {
  elFontSize.append(elNew("option", {
    textContent: `${i}px`,
    value: `${i}px`
  }));
}

const commandsGet = () => {
  // If we have no commands stored in localStorage, save them!
  if (!localStorage.commands) commandsSave();
  // Convert string from localStorage to Object Literal
  const commands = JSON.parse(localStorage.commands);
  // Apply values to DOM input/select elements by name
  Object.entries(commands).forEach(([name, value]) => {
    el(`[name="${name}"]`).value = value;
  });
};

const commandsSave = () => {
  // Create an Object of the commands to save to localStorage
  const commands = [...elsCommand].reduce((obj, elem) => {
    obj[elem.name] = elem.value;
    return obj;
  }, {});
  // Convert object Literal to String and save to localStorage
  localStorage.commands = JSON.stringify(commands);
};

const commandsApply = () => {
  // Apply styles to the desired contenteditable element:
  Object.assign(elEditable.style, JSON.parse(localStorage.commands));
};

// Assign an event listener to all your inputs/selects to store and apply the 
// styles (commands) on "input"
elsCommand.forEach(elem => {
  elem.addEventListener("input", () => {
    commandsSave();
    commandsApply();
  });
});

// Init:
// On page load read the commands from LocalStorage
// and apply them to your editable element
commandsGet();
commandsApply();
/*QuickReset */

* {
  margin: 0;
  box-sizing: border-box;
}

.paragragh {
  margin: 10px auto;
  min-width: 400px;
  min-height: 300px;
  background-color: #ddd;
  text-align: center;
  padding-top: 30px;
}
<form id="formSettings">
  <select class="command" name="fontFamily">
    <option value="Arial">Arial</option>
    <option value="Times New Roman">Times New Roman</option>
    <option value="Courier New">Courier New</option>
  </select>
  <select class="command" name="color">
    <option value="black">Black</option>
    <option value="green">Green</option>
    <option value="blue">Blue</option>
    <option value="red">Red</option>
    <option value="purple">Purple</option>
  </select>
  <select class="command" name="fontSize"></select>

  <div id="editable" contenteditable="true">Lorem ipsum dolor sit amet consectetur adipisicing elit.</div>
</form>
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文