由于每次刷新都会覆盖唯一ID,因此无法创建唯一ID

此函数称为表单提交,并且进一步调用用于呈现div列表的新函数。完成此操作后,由于拖放功能,网站被刷新。问题是我似乎无法找到一种方法来创建唯一的ID,该ID会通过页面刷新而保持不变,并且由于例如“ let taskId = 0”而不会在页面加载时被覆盖。

有任何想法吗? :)

function createNewTask(event){
    if(document.querySelector("[name='description']").value === ""){
        alert("Cannot add empty task.");
    }else {
        event.preventDefault();


        let taskId = 0;
        const description = document.querySelector("[name='description']").value;
        const givenTo = document.querySelector("[name ='givenTo']").value;
        const createdByName = document.querySelector("[name = 'workerName']").value;
        const task = {taskId, description, givenTo, createdByName, section: 'task-section'};
        const taskList = JSON.parse(window.localStorage.getItem("taskList")) || [];

        taskId++;
        taskList.push(task);
        window.localStorage.setItem("taskList", JSON.stringify(taskList));
        // renderTaskList();
        renderStoredList();

        //Reload page after createNewTask to activate draggable
        location.reload();


    }  
}
评论
yeahlife
yeahlife

As I cannot add a comment, I'll post it here as an answer. What I would do on my end to keep track of the taskId is to also store the latest taskId that was last used in my localStorage, that way, it would persist.

window.localStorage.setItem('lastTaskId', taskId);

然后,只需在每次页面加载时进行处理即可。 希望这可以帮助!

点赞
评论