-1
I’m learning to use javascript, I’m following a tutorial,I’ve reviewed the code, it looks identical, but it just doesn’t save. After I update the page which I delete or added does not keep, back to the default.
The code:
//referenciando os elementos
var listElement = document.querySelector('#app ul');
var inputElement = document.querySelector('#app input');
var buttonElement = document.querySelector('#app button');
//armazenamento de ToDo no JS
var todos = JSON.parse(localStorage.getItem('list_todos')) || [] ;
//To do padrão
var todos = [
'Fazer cafe',
'Estudar Java',
'Estudar JavaScript'
];
//função para renderizar toDO
function renderTodos(){
listElement.innerHTML = ''; //removendo o conteudo do listelement
//for para arrays
for (todo of todos){
//criando os elementos
var todoElement = document.createElement('li');
var todoText = document.createTextNode(todo);
todoElement.appendChild(todoText);
listElement.appendChild(todoElement);
//excluindo elementos
var linkElement = document.createElement('a');
var linkText = document.createTextNode('Excluir');
linkElement.appendChild(linkText);
todoElement.appendChild(linkElement);
linkElement.setAttribute('href', '#'); //href do 'a'
//identificar qual remover(pos)
var pos = todos.indexOf(todo);
linkElement.setAttribute('onclick', 'deleteTodo(' + pos + ')');
}
}
renderTodos();
//função adicionar to do
function addTodo(){
var todoText = inputElement.value; //valor do input
todos.push(todoText);//adicionar no aray
inputElement.value = ''; //apaga o atual
renderTodos(); //renderizar novamente
saveToStorage();
}
//botao para adicionar o todo
buttonElement.onclick = addTodo;
//função para excluir
function deleteTodo(pos){
todos.splice(pos, 1); //remove uma quantidade de item
renderTodos();
saveToStorage();
}
//função de salvamento
function saveToStorage(){
localStorage.setItem('list_todos', JSON.stringify (todos));
}
THE HTML:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<div id="app">
<ul> </ul>
<input type="text" placeholder="Digite um todo" />
<button>Adicionar</button>
</div>
<script src="JSAPP.js"></script>
</body>
</html>
(it seems to be working, but on the screen it shows the opposite)
It worked, thanks a lot. Interesting that I reviewed the tutorial to be sure and yes, it was the same (the rocketseat), I do not know the pq of this, but thank you very much for solving my problem.
– Lucas RM