表单值的JavaScript问题

时间:2017-11-28 18:09:11

标签: javascript html

单击按钮时我需要更新值,但不起作用。我只得到空阵列。

var title = form.title.value;
var data = form.date.value;
var priority = form.priority.value;
var description = form.textarea.value;
var check = form.check.value;

document.querySelector("button").addEventListener('click', function() {
    var obj = {};
    var arr = [];
    obj.title = title;
    obj.date = data;
    obj.priority = priority;
    obj.description = description;
    obj.check = check;
    arr.push(obj);
    localStorage.setItem('todo_list', JSON.stringify(arr));
    var tasks = JSON.parse( localStorage.getItem('todo_list') );
    console.log(tasks);
});

1 个答案:

答案 0 :(得分:1)

您在代码首次运行时获取所有表单值,可能是在加载页面时。单击按钮后,您不应该取出它们吗?删除顶部的所有五个var语句,并直接在click事件侦听器中获取表单值:

document.querySelector("button").addEventListener('click', function() {
    var obj = {};
    var arr = [];
    obj.title = form.title.value;
    obj.date = form.date.value;
    obj.priority = form.priority.value;
    obj.description = form.textarea.value;
    obj.check = form.check.value;
    arr.push(obj);
    localStorage.setItem('todo_list', JSON.stringify(arr));
    var tasks = JSON.parse( localStorage.getItem('todo_list') );
    console.log(tasks);
});

您还可以通过设置对象/数组文字中的所有值来清理代码。根据您的需要,这可能是一种更好的方法:

document.querySelector("button").addEventListener('click', function() {
    var arr = [
        {
            title: form.title.value,
            date: form.date.value,
            priority: form.priority.value,
            description: form.textarea.value,
            check: form.check.value
        }
    ];
    localStorage.setItem('todo_list', JSON.stringify(arr));
    var tasks = JSON.parse( localStorage.getItem('todo_list') );
    console.log(tasks);
});