繁体   English   中英

使用 javascript 将文本条目保存到本地存储

[英]Using javascript to save a text entry to local storage

我正在尝试使用 javascript 来保存使用本地存储的文本条目,但收效甚微,因为我是 javascript 的新手,任何人都可以提供任何建议。这是一个基本的博客帖子站点,用户可以在其中将文本提交到日记条目中。 我特别不确定如何获取文本区域元素的当前值,如下面的代码所示,我认为这就是我出错的地方。

 function addTextEntry(itemKey, initialText, isNewEntry) { // Create a textarea element to edit the entry var textElement = document.createElement("textarea"); textElement.rows = 5; textElement.placeholder = "(new entry)"; textElement.value = initialText; addSection(itemKey, textElement); // If this is a new entry (added by the user clicking a button) // move the focus to the textarea to encourage typing if (isNewEntry) { textElement.focus(); } // Create an event listener to save the entry when it changes function saveEntry() { console.log("saveEntry called with variables in scope:", { itemKey, initialText, isNewEntry, textElement, }); // Save text entry //...get the textarea element's current value textElement = document.getElementById; //...make a text item using the value textElement.value = initialText; // (demonstrated elsewhere in this file) //...store the item in local storage using the given key localStorage.setItem(itemKey); } // Connect the saveEntry evenFt listener to the textarea element 'change' event textElement.addEventListener("change", saveEntry); // (demonstrated elsewhere in this file) }

看起来您使用的getElementById有误。

尝试以下方法获取<textarea>的当前值:

 function logTextareaValue () { const element = document.getElementById('myTextarea') const value = element.value console.log(value) }
 <textarea id="myTextarea">Default text</textarea> <button onClick="logTextareaValue()">Click to log textarea value to console</button>

在您的代码中,您只将一个参数itemKey传递给setItem()方法。 您还应该将该键的值作为第二个参数传递。

localStorage.setItem(itemKey, itemValue);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM