1

Всем привет, Не сохраняются данные в Local Storage, помогите пожалуйста

function onPageLoaded() {
    const ul = document.querySelector("ul.todos");

    const addButton = document.querySelector('button.addButton');
    const input = document.querySelector('.input_task');
    const mainDiv = document.querySelector('div.container');

    const changeButton = document.querySelector('i.change');//змінити
    const saveButton = document.querySelector('i.save');//зберегти
    const clearButton = document.querySelector('i.clear')//очистити


    changeButton.addEventListener('click', () => {
        localStorage.setItem('todos', ul.innerHTML);
    });

    saveButton.addEventListener('click', () => {
        localStorage.setItem('todos', ul.innerHTML);
    });

    clearButton.addEventListener('click', () => {
        localStorage.setItem('todos', ul.innerHTML);
    });


    addButton.addEventListener('click', () => {
        createTodo();
        //toLocal();
    });
    saveButton.addEventListener('click', () => {
        localStorage.setItem('container', mainDiv.innerHTML);
    });


    //Функция на добавление задачи
    function createTodo() {
        const div = document.createElement('div');
        div.classList.add('block');
        /*path 1*/
        const div_data = document.createElement('div');
        div_data.classList.add('data');
        const p_data__number = document.createElement('p');
        p_data__number.classList.add('data__number');
        const p_data__time = document.createElement('p');
        p_data__time.classList.add('data__time');



       let date = new Date();
        let day = date.getDate();
        let month = date.getMonth() + 1;
        let year = date.getFullYear();
        let hours = date.getHours();
        let minutes = date.getMinutes();


        if (day < 10) {
            day = "0" + day;
        }

        if (month <10) {
            month = "0" + month;
        }
        if (hours < 10) {
            hours = "0" + hours;
        }

        if (minutes <10) {
            minutes = "0" + minutes;
        }
        let currentDate = day + "." + month + "." + year;
        let time = hours + ":" + minutes;

        p_data__number.innerHTML =  currentDate;
        p_data__time.innerHTML = time;


        /*path 2*/
    const p_block_number = document.createElement('p');
    p_block_number.classList.add('block_number');
    p_block_number.innerHTML = '1';//не запрограммирован счетчик

    /*path 3*/
       const div_block_angle = document.createElement('div');
        div_block_angle.classList.add('block_angle');
        const li_task_wrapper = document.createElement('li');
        li_task_wrapper.classList.add('task_wrapper');
        const i_up = document.createElement('i');
        i_up.classList.add('fa', 'fa-angle-up');
        const i_down = document.createElement('i');
        i_down.classList.add('fa', 'fa-angle-down');

        /*path 4*/
        const ul = document.createElement('ul');
        ul.classList.add('todos');
        const li = document.createElement('li');
        const textSpan = document.createElement('span');
        textSpan.classList.add('block_input');
        const newTodo = input.value;
        textSpan.append(newTodo);//Добавляет в спан текст введенный в поле ввода

        /*path 5*/
        const pencilIcon = document.createElement('i');
        pencilIcon.classList.add('fa', 'fa-pencil');

        /*path 6*/
        const checkIcon = document.createElement('i');
        checkIcon.classList.add('fa', 'fa-check');

        /*path 7*/
        const delIcon = document.createElement('i');
        delIcon.classList.add('fa', 'fa-trash');

        /*вывод на экран*/
        /*path 1*/
        mainDiv.appendChild(div).appendChild(div_data).appendChild(p_data__number);
        //выводим на экран дату
        mainDiv.appendChild(div).appendChild(div_data).appendChild(p_data__time);
        //выводим на экран время,

        /*path 2*/
        mainDiv.appendChild(div).appendChild(p_block_number);

        /*path 3*/
        mainDiv.appendChild(div).appendChild(div_block_angle).appendChild(li_task_wrapper).appendChild(i_up);
        mainDiv.appendChild(div).appendChild(div_block_angle).appendChild(li_task_wrapper).appendChild(i_down);

        /*path 4*/
        mainDiv.appendChild(div).appendChild(ul).appendChild(li).appendChild(textSpan);

        /*path 5*/
        mainDiv.appendChild(div).appendChild(pencilIcon);

        /*path 6*/
        mainDiv.appendChild(div).appendChild(checkIcon);

        /*path 7*/
        mainDiv.appendChild(div).appendChild(delIcon);

        input.value = "";
        listenDeleteTodo(delIcon);

      
    }

    //Функция удаления задачи
    function listenDeleteTodo(element) {
        element.addEventListener('click', (event) => {
            element.parentElement.remove();
            event.stopPropagation();
        });
        //toLocal();
    }

    //Функция для сохранения задач после перезагрузки
    function loadTodos() {
        const data = localStorage.getItem('container');
        if (data) {
            mainDiv.innerHTML = data;
        }
        const deleteButtons = document.querySelectorAll('i.fa-trash');
        for (const button of deleteButtons) {
            listenDeleteTodo(button);
        }
    }
    //Вызываем функцию loadTodos сразу при загрузке страницы
    loadTodos();

}
document.addEventListener('DOMContentLoaded', onPageLoaded);







function myData(dateId, timeId) //Выводит дату по клику, РАБОТАЕТ
{
    temp_date = new Date();
    day = temp_date.getDate();
    month = temp_date.getMonth() + 1;
    year = temp_date.getFullYear();
    hours = temp_date.getHours();
    minutes = temp_date.getMinutes();

    if (day < 10) {
        day = "0" + day;
    }

    if (month <10) {
        month = "0" + month;
    }
    if (hours < 10) {
        hours = "0" + hours;
    }

    if (minutes <10) {
        minutes = "0" + minutes;
    }
    document.getElementById(dateId).innerHTML = day + "." + month + "." + year;
    document.getElementById(timeId).innerHTML = hours + ":" + minutes;
    //toLocal();
}

// Добавление тасков
const addButton = document.getElementById('add');
    //addButton.className = "button";
const inputTask = document.getElementById('inp');
//inputTask.className = "input_task";
const unfinishedTasks = document.getElementById('unfinished_tasks');
//unfinishedTasks.className = "todos";
const finishedTasks = document.getElementById('finished_tasks');

function createNewElement(task) {
    let listItem = document.createElement('li');
    let checkbox = document.createElement('span');//Создаем элемент
    checkbox.className = "span_value";//Задаем класс элементу
    checkbox.innerHTML = task;
    //checkbox.innerHTML = "<i class="fa fa-sort-asc fa-2x" aria-hidden="true"></i>";
    //Вставляем элемент внутрь - checkbox
    listItem.appendChild(checkbox);
    return listItem;
    //toLocal();
}

function addTask() {
    if (inputTask.value.length > 0) {
        let listItem = createNewElement(inputTask.value);
        unfinishedTasks.appendChild(listItem);
        inputTask.value = "";
    }

addButton.onclick = addTask;
    //toLocal();
}


function changePriorityUp() {
    let priorityValue1 = document.getElementById('1');
        counter = priorityValue1.textContent;
    console.log(priorityValue1);
        if (priorityValue1.textContent < 9) {
           ++counter;
            priorityValue1.innerHTML = counter;
        }
    //toLocal();
}


function changePriorityDown() {
   let priorityValue1 = document.getElementById('1');
    counter = priorityValue1.textContent;
    if (priorityValue1.textContent > 0) {
        --counter;
        priorityValue1.innerHTML = counter;
    }
    //toLocal();
}

document.addEventListener("DOMContentLoaded", onPageLoaded);
*{
    /*border: 1px solid red;*/
    margin:0;
    padding:0;
    box-sizing: border-box;
}
.container {
    margin: 0 auto;
    max-width: 1300px;
}
h1 {
    font-family: sans-serif;
    font-weight: 600;
    color: #373737;
    font-size: 100%;
    margin: 5% 0 2% 38%;
}
input {
    border: 0;
    color: #bcbcbc;
    white-space: normal;
    text-align: left;
    padding-left: 5px;
}

.input_task {
    border-bottom: 2px solid #e1e1e1;
    width: 625px;
    height: 24px;
}
.input_add {
    display: flex;
    flex-direction: row;
    text-align: center;
    margin-left: 123px;
    height: 30px;
    color: white;
}

#add {
    padding: 10px 0;
    width: 110px;
    height: 20;
    background: #0097f4;
    border: 0;
    color: white;
    border-radius: 4px;
    box-shadow: 0 2px 3px rgba(0,0,0,.5);
    margin-left: 20px;
}

.sort {
    display: flex;
    flex-direction: row;
    margin-top: 20px;

}
.number {
    margin: 5px 20px 0 20px;
    display: flex;
    flex-direction: column;
    width: 25px;
    align-items: center;
}
.search{
    margin-left: 40px;
    margin-top: 10px;
    width: 514px;
    height: 38px;
    border-bottom: 2px solid #a6a6a6;
}
.number p {
    color: #ada6a7;
    font-family: sans-serif;
    font-weight: 600;
}

.fa-sort {
    color: #ada6a7;
    margin: 0 40px;
}
.fa-sort-asc {
    color: #ada6a7;
    margin-bottom: -19px;
}
.fa-sort-desc{
    color: #ada6a7;
    margin-top: -21px;
}
.fa-search {
    color: #ada6a7;
    margin-top: 14px;
    left: -39%;
    position: relative;
    z-index: 1;
    float: left;
}
.fa-filter {
    color: #ada6a7;
    margin: 14px 0 0 47px;
}

.block {
    display: flex;
    flex-direction: row;
    margin-top: 20px;
}
.data {
    display: flex;
    flex-direction: column;
    align-items: center;
    padding: 0 18px 0 10px;
}
.data__number {
    font-size: 135%;
}
.data__time {

}

.block_number {
    padding: 5px 14px;
    margin: 7px 0;
    background: #717171;
    color: white;
    font-family: sans-serif;
    height: 26px;
}
.block_angle {
    display: flex;
    flex-direction: column;
    margin: 7px 10px 0 20px;
}
.block_input {

    color: black;
    width: 516px;
    border-radius: 4px;

}
li {
    list-style-type: none;
}

.todos {
    height: 55px;
    width: 516px;
    border: 1px solid red;
    padding-top: 18px;
    background: #eeeeee;
    /*display: flex;
    justify-content: center;
    text-align: center;*/
}
.block_input2 {
    background: #d1eef4;
    color: black;
    width: 516px;
}
.block_input3 {
    background: #eeeeee;
    color: black;
    width: 516px;
    height: 100px;
}
.fa-angle-up {
    color: #0097f4;
}
.fa-angle-down {
    color: #0097f4;
}
.fa-pencil {
    border-radius: 50%;
    background: #3f8c3f;
    padding: 11px;
    color: white;
    margin: 8px 12px 0 12px;
    height: 38px;
    box-shadow: 0 2px 3px rgba(0,0,0,.5);
}
.fa-check {
    border-radius: 50%;
    background: #0097f4;
    padding: 11px;
    color: white;
    margin: 8px 12px 0 12px;
    height: 38px;
    box-shadow: 0 2px 3px rgba(0,0,0,.5);
}
.fa-trash {
    border-radius: 50%;
    background: #0097f4;
    padding: 11px;
    color: white;
    margin: 8px 12px 0 12px;
    height: 38px;
    box-shadow: 0 2px 3px rgba(0,0,0,.5);
}
.small a {
    padding: 7px 28px;
    font-size: 90%;

}
a.not_active {
    background: #eeeeee;
    box-shadow: 0 0 0 rgba(0, 0, 0, 0);
    color: #0097f4;
}
.delete {

    width: 14%;
    height: 99px;
    background: #eeeeee;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    position: absolute;
    z-index: 2;
    right: 11%;
    top: 29%;
}
.edit {

    width: 21%;
    height: 220px;
    background: #eeeeee;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    position: absolute;
    z-index: 3;
    right: 5%;
    bottom: 29%;
}
h2 {
    font-family: sans-serif;
    margin-bottom: 22px;
    font-size: 120%;
}
h3 {
    font-family: sans-serif;
    margin-bottom: 15px;
}
p {
    font-family: sans-serif;
}
.edit__box {
    background: #fffafa;
    height: 60%;
    width: 80%;
    margin: -10px 0 13px 0;
    display: flex;
    align-items: center;
}
.line {
    border-right: 2px solid #e1e1e1;
    width: 3px;
    height: 270px;
    position: absolute;
    z-index: 4;
    right: 30%;
    bottom: 43%;
}
<!doctype html>
<html lang="ru">
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <!-- <meta charset="UTF-8"> -->
    <title>Home Work js</title>
    <link rel="stylesheet" href="css/style.css">
    <script src="https://kit.fontawesome.com/0a8ce8c2c2.js" crossorigin="anonymous"></script>
    <script src="js/script.js"></script>
</head>
<body>
<div class="container" id="container">
    <h1>TODO LIST</h1>
    <div class="input_add">
        <input type="text" name="name" placeholder="Task" class="input_task" id="inp">
        <!-- <div class="button">
        </div> -->
        <button class="addButton" onclick="addTask()" id="add">ADD</button>
    </div>
    <div class="sort">
        <i class="fa fa-sort fa-3x" aria-hidden="true"></i>
        <div class="number">
            <i class="fa fa-sort-asc fa-2x" aria-hidden="true"></i>
            <p>123</p>
            <i class="fa fa-sort-desc fa-2x" aria-hidden="true"></i>
        </div>
        <input name="name" value="" class="input_task search">
        <i class="fa fa-search fa-2x" aria-hidden="true"></i>
        <i class="fa fa-filter fa-2x" aria-hidden="true"></i>
    </div>
    <div class="block" id="block">
        <div class="data">
            <p class="data__number" id="current_date_time_block">12.10.2018</p> <!-- onload="myData()" -->
            <p class="data__time" id="current_time_block">13:24</p>
        </div>
        <p class="block_number" id="1">1</p>
        <div class="block_angle">
            <li class="task_wrapper">
                <i class="fa fa-angle-up chengePriorityButton-up" onclick="changePriorityUp()" aria-hidden="true"></i>
                <i class="fa fa-angle-down" onclick="changePriorityDown()" aria-hidden="true"></i>
            </li>
        </div>
        <ul class="todos" id="unfinished_tasks">
            <li>
                <span onclick="myData('current_date_time_block', 'current_time_block')" class="block_input"
                id="span_value">Вымыть кухню
                </span>
            </li>
        </ul>
        <i class="fa fa-pencil change" aria-hidden="true"></i>
        <i class="fa fa-check save" aria-hidden="true"></i>
        <i class="fa fa-trash clear" aria-hidden="true"></i>
    </div>

    <!-- <div class="delete delete_active">
        <h2>Delete Item?</h2>
        <div class="button small">
            <a class="not_active">NO</a>
            <a>YES</a>
        </div>
    </div>

    <div class="edit edit_active">
        <h3>Edit text</h3>
        <div class="edit__box">
            <p>New text of todo item...</p>
        </div>
        <div class="button small">
            <a class="not_active">CANSEL</a>
            <a>SAVE</a>
        </div>

    </div>
    <div class="line">
    </div>-->

</div>
</body>
</html>

3
  • В чём возникла сложность? Добавьте Ваш код сохранения данных в localstorage.
    – Denis640Kb
    12 фев 2020 в 21:02
  • Уже Добавил код 12 фев 2020 в 21:06
  • Уменьшите Ваш пример в десять раз.
    – user176262
    12 фев 2020 в 21:08

1 ответ 1

0

Все Ваши переменные, назначенные в начале onPageLoaded, (кроме mainDiv) будут указывать на элементы, которых после mainDiv.innerHTML = ... уже нет в дереве элементов страницы.

Перенесите mainDiv.innerHTML = ... в самое начало функции.

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.