JS代码
var response = document.querySelector('#name').value;
localStorage.getItem('li')
localStorage.setItem('li', response)
document.addEventListener("DOMContentLoaded", () => {
document.querySelector('#submit').disabled = true;
document.querySelector('#name').onkeyup = () => {
// checking whether the input bar is empty or not
if (document.querySelector('#name').value.length > 0)
document.querySelector('#submit').disabled = false;
else document.querySelector('#submit').disabled = true;
};
window.onload = () => {
document.querySelector('form').onsubmit = () => {
//Crearting a list item
const li = document.createElement('li');
li.innerHTML = localStorage.getItem('id')
//Appending it to the unordered list
document.querySelector('.unordered').append(li);
//Clear input feild
document.querySelector('#name').value = "";
document.querySelector('#submit').disabled = true;
//Stop form from submitting
return false;
};
};
});
HTML代码
{% extends "base.html" %}
{% block head %}
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css"
integrity="sha384-9aIt2nRpC12Uk9gS9baDl411NQApFmC26EwAOH8WgZl5MYYxFfc+NcPb1dKGj7Sk" crossorigin="anonymous">
<title>Creating new channel</title>
<link rel="stylesheet" href="{{url_for('static', filename = 'css/main.css')}}" />
<script src="{{url_for('static', filename = 'js/button.js')}}"></script>
{% endblock %}
{% block body %}
<img src="{{url_for('static', filename = 'images/Logo.png')}}">
<div class="form-div">
<form class="form-group">
<input type="text" id="name" class="form-control" placeholder="Create Channel" autocomplete="off" /><br />
<button type="submit" class="btn btn-success" id="submit">Create Channel</button>
</form>
<ol class="unordered"></ol>
</div>
{% endblock %}
</html>
我试图创建一个待办事项列表,因此,为了永久存储数据,即使在浏览器关闭时,我也使用本地存储。但是,当我在这里使用本地存储时,它不起作用(当我刷新页面时,所有内容都被擦除)。在控制台中运行查询localstorage时。getItem('li'),然后是localstorage。setItem('li',response),则显示用户输入的值,但无法永久存储。那么是我的代码错了还是有逻辑错误呢。
您正在编写li.inner超文本标记语言=localStorage.get项目('id')
内document.querySelector('form'). on提交
。因此,只有在提交表单时才会执行此操作。要正常显示它,您必须将它从这个函数中取出,并放入window.load
中。
大概是这样的:
window.onload = () => {
const li = document.createElement('li');
li.innerHTML = localStorage.getItem('id') ?
localStorage.getItem('id') : "";
document.querySelector('.unordered').append(li);
document.querySelector('form').onsubmit = () => {
//Crearting a list item
const li = document.createElement('li');
li.innerHTML = localStorage.getItem('id');
...
};
};