Я новичок в программировании и JavaScript. Я пытаюсь добавить прослушиватель событий, чтобы при вводе пользователем текста он сохранялся в локальном хранилище и находился на странице при перезагрузке. Я настроил функцию diaryText()
, чтобы получить значение, превратить его в текстовый элемент и сохранить его. Прослушиватель событий был добавлен, но я не думаю, что получил правильный код.
// Make diary data item
function makeItem(type, data) {
var itemObject = { type: type, data: data };
return JSON.stringify(itemObject);
}
// Add a text entry to the page
function addTextEntry(key, text, isNewEntry) {
// Create a textarea element to edit the entry
var textareaElement = document.createElement("TEXTAREA");
textareaElement.rows = 5;
textareaElement.placeholder = "(new entry)";
// Set the textarea's value to the given text (if any)
textareaElement.value = text;
// Add a section to the page containing the textarea
addSection(key, textareaElement);
// If this is a new entry (added by the user clicking a button)
// move the focus to the textarea to encourage typing
if (isNewEntry) {
textareaElement.focus();
}
// Make an event listener to save text when it changes:
// ...get the textarea element's current value
function diaryText() {
var data = textareaElement.value;
// ...make a text item using the value
// (demonstrated elsewhere in this file)
var item = makeItem("text", data);
// ...store the item in local storage using the given key
localStorage.setItem(key, item);
}
// Function to connect event listeners and start the application
function initialize() {
// A rough check for local storage support
if (!window.localStorage) {
// This could be more elegant too
document.querySelector("main").outerHTML =
"<h1>Error: localStorage not supported!</h1>";
// Stop the demo
return;
}
// Connect the event listener to the textarea element:
textareaElement.addEventListener("onblur", diaryText);
// Connect the input file selected event listener
// (note this may not trigger if you repeatedly select the same file)
var inputElement = document.querySelector("#image input");
inputElement.addEventListener("change", processFile);
// Create some demonstration items
createDemoItems();
// Update the page to reflect stored items
showEntries();
}
// Connect event listeners and start the application when the page loads
window.addEventListener("load", initialize);
}
HTML Код:
<main>
<section id="text" class="button">
<button type="button">Add entry</button>
</section>
<section id="image" class="button">
<button type="button">Add photo</button>
<input type="file" accept="image/*" />
</section>
</main>