下午好,我希望能得到一些指导。我是JavaScript的新手,正在为一个项目而奋斗。我们被要求将新条目存储到一个网站应用程序中,该应用程序曾经将存储添加到本地存储中。
到目前为止,这就是我所拥有的,但我不知道如何将它存储在错误的位置。
被**包围的第一部分工作正常(尽管它不存储所有内容)。这是我尝试添加新代码以存储消息和调用事件侦听器的最后一步,而事件侦听器不起作用。
如有任何指导,将不胜感激。
**function addTextEntry(itemKey, initialText, isNewEntry) {
// Create a text element to edit the entry
var textElement = document.createElement("textarea");
textElement.rows = 5;
textElement.placeholder = "(new entry)";
// Set the textarea's value to the given text (if any)
textElement.value = initialText;
// Add a section to the page containing the textarea
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() {
// A new version of this function is created every time addTextEntry is called,
// so it can access all the variables available in this call to addTextEntry
console.log("saveEntry called with variables in scope:", {
itemKey,
initialText,
isNewEntry,
textElement,
});
document.getElementById(initialText);
item = makeTextItem(initialText);
localStorage.setItem(itemKey);
textElement.addEventListener("initialText", saveEntry);
}
}发布于 2022-03-05 17:01:37
setItem方法采用两个参数:
keyName:本地StoragekeyValue:中密钥的名称--给定键的值
在您的代码中,您只传递一个参数itemKey。您还应该将该键的值作为第二个参数传递。
发布于 2022-03-05 17:03:32
document.getElementById(initialText);这个语句对结果没有任何作用。您可能希望将其赋值为类似于const textElement = document.getElementById(initialText);的值。
item = makeTextItem(initialText);您遗漏了makeTextItem的代码,但这仍然无关紧要,因为在代码下面的任何地方都没有使用item。
localStorage.setItem(itemKey);setItem采用两个参数,键和想要保存storage.setItem(keyName, keyValue);的东西。
textElement.addEventListener("initialText", saveEntry);addEventListener的第一个参数应该是有效的事件。addEventListener(type, listener);
https://stackoverflow.com/questions/71364097
复制相似问题