Хранение значения флажка в локальном хранилище - PullRequest
0 голосов
/ 18 декабря 2018

Since I cant run the code snippet on here, this is how the checklist looks so far Я работаю над приложением Chrome для контрольного списка и буду рад вашей помощи.В принципе, я не могу понять, как сохранить статус флажка.Если я поставлю флажок и обновлю страницу, я бы хотел, чтобы она оставалась отмеченной.Но я не могу закодировать это.Есть идеи как это сделать?Спасибо !!

Редактировать: Я добавил HTML, он дает мне сообщение, что мой пост в основном код и что мне нужно добавить текст, поэтому здесь я просто пишу еще немного, чтобы выполнить это требование.Нет необходимости читать это.Спасибо за помощь и извините за позднюю правку

function get_todos() {
    var todos = new Array;
    var todos_str = localStorage.getItem('todo');
    if (todos_str !== null) {
        todos = JSON.parse(todos_str); 
    }
    return todos;
}
 
function add() {
    var task = document.getElementById('task').value;
 

    var todos = get_todos();
	
    todos.push(task);
    localStorage.setItem('todo', JSON.stringify(todos));
 
    show();
 
    return false;
}
 
function remove() {
    var id = this.getAttribute('id');
    var todos = get_todos();
    todos.splice(id, 1);
    localStorage.setItem('todo', JSON.stringify(todos));
 
    show();
 
    return false;
}
 
function show() {
    var todos = get_todos();
 
    var html = '<ul>';
    for(var i=0; i<todos.length; i++) {
        html += '<li>' + '<input type="checkbox" id="checkbox">' + todos[i] + '<button class="remove" id="' + i  + '">delete</button></li>' ;
    
	
	};
    html += '</ul>';
	
 
    document.getElementById('todos').innerHTML = html;
	
	
	
	
    var buttons = document.getElementsByClassName('remove');
    for (var i=0; i < buttons.length; i++) {
        buttons[i].addEventListener('click', remove);
    };
}



document.getElementById('add').addEventListener('click', add);
show();
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=yes">
</head>
<body>


<style>
html,body,h1,h3,h4,h6 {font-family: "Roboto";font-size: 24px; sans-serif}
h2 {font-family: "Roboto";font-size: 36px; sans-serif}
h5 {font-family: "Roboto";font-size: 28px; sans-serif}
</style>



<input id="task"><button id="add">Add</button>
<hr>
<div id="todos"></div>


<script src="todo.js"></script>


   
</body>
</html>

1 Ответ

0 голосов
/ 18 декабря 2018

Поскольку никто не дал ответа, я решил добавить свое потенциальное решение, я выбрал функциональный стиль, потому что почему бы и нет, он прост, легко читается и т. Д ...

PS

Я включил резервную переменную, потому что при переполнении стека вы не можете получить доступ к локальному хранилищу при запуске сниппета.

let fallback = [];
const $e = query => document.querySelector(query);


// Return a todo list.
const getToDoList = () => {
  let data = null;
  
  try {
    data = JSON.parse(localStorage.getItem('todo'));
  } catch (e) {
    data = fallback;
  }
  
  return data == null || Array.isArray(data) == false ? [] : data;
};


// Set the todo list.
const setToDoList = (data) => {
  try {
    localStorage.setItem('todo', JSON.stringify(data));
  } catch (e) {
    fallback = data;
  }
};


// Add a task to the todo list.
const addToDo = () => { 
  const array = getToDoList();
  array.push({value: $e("#task").value, checked: false});
  setToDoList(array);
}; 


// Remove a task from the todo list.
const removeToDo = index => {
  const array = getToDoList();
  array.splice(index, 1);
  setToDoList(array);
};


// Allow for the ability to remove an item from the todo list & other stuff..
const dispatchListEvents = () => {
  document.querySelectorAll('#app ul li span').forEach(span => {
    span.onclick = () =>  {
      removeToDo(span.parentElement.getAttribute('data-index'));
      render();
    }
  });
  
  document.querySelectorAll('#app ul li input').forEach(input => {
    input.onclick = () =>  {
      const array = getToDoList();
      const object = array[input.parentElement.getAttribute('data-index')];
      object.checked = ! object.checked;
      setToDoList(array);
      render();
    }
  });
};


// Render the todo list.
const render = () => {
  let index = 0;
  const template = item => `<li data-index="${index++}">` +
      `<input type="checkbox" ${item.checked ? 'checked' : ''} />` +
      `${item.value} <span>X</span></li>`;
  
  const re = new RegExp('</li>,', 'g'), replacement = '</li>';
  const html = `<ul>${getToDoList().map(i => template(i))}</ul>`;
  $e("#app").innerHTML = `${html.replace(re, replacement)}`;
  dispatchListEvents();
};


// Allow the user to add a task to the todo list.
const addToListClickHandler = () => {
  let result = $e("#task").value.replace(/\ /g, '').length > 0 ? addToDo() : null;
  $e("#task").value = null; // Always null as addToDo returns null.
  render();
};


// The function that will be fired when the DOM is ready.
const ready = () => {
  render(); // Initial render.
  $e("#addToList").addEventListener('click', addToListClickHandler);
};


// An insanely lazy implementation of $(document).ready.
const delay = 250;
const fakeOnReady = setTimeout(ready, delay);
body {
  font-family: Arial, Helvetica, sans-serif;
}

#app ul li {
  max-width: 150px;
}

#app ul li span {
  float: right;
  color: red;
}

#app ul li span:hover {
  cursor: pointer;
}
<h1>To Do List</h1>

<section>
  <h2>Add Task</h2>
  <input id="task" placeholder="Task..."/>
  <input type="button" id="addToList" value="Add"/>
</section>

<hr/>

<section>
  <h2>Tasks</h2>
  <div id="app">
    <!-- Area for the DHTML. -->
  </div>
</section>
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...