получение EventListener для хранения текста при загрузке страницы - PullRequest
0 голосов
/ 25 февраля 2020

Я новичок в программировании и 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>

1 Ответ

0 голосов
/ 25 февраля 2020

К сожалению, фрагмент кода здесь заблокирован от использования lcoalStorage. Однако вы можете проверить это в jsfiddle или скопировать и вставить в собственный файл html и открыть его в браузере.

https://jsfiddle.net/81no5jxh/

<style>textarea{display: flex;}</style>

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<textarea id="textarea"></textarea>
<button id="button">save</button>

<script>
    var $textarea = $("#textarea");
    var $button = $("#button");

    function initialize(){
      if(!window.localStorage){return alert("Error: localStorage not supported!");}

      var _startingMessage = window.localStorage.getItem("message_key") || "";
      $textarea.val(_startingMessage)
      $button.on("click", _handleButtonClick);
    }

    function _handleButtonClick(){
        localStorage.setItem("message_key",$textarea.val())
    }

    window.addEventListener("load", initialize);
</script>
...