Web-使用LocalStorage API和jQuery删除选定的列表项 [英] Web - Deleting chosen list items with the LocalStorage API and jQuery

查看:83
本文介绍了Web-使用LocalStorage API和jQuery删除选定的列表项的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

作为一个或多或少的概念验证,我想使用LocalStorage API将列表项保存到存储中.我想出的方法有点复杂且效率低下,但是直到删除单个列表项用例为止,它的工作情况还是不错的.这是大致的工作方式.使用localStorage.length,我使用Javascript来给注释添加一个"id".这样,我可以使用for循环从第一个注释迭代到localStorage.length,并在两次执行之间的页面加载期间将每个注释附加到HTML页面.此外,使用此ID,我可以确定使用jQuery单击了哪个注释.问题在于删除注释.我可以删除用户单击的笔记,但是如果我不对那些在存储中创建孔"的笔记列表进行重新排序.有什么想法吗?

在此处进行实时演示,但也许不支持localStorage API: https://jsfiddle.net/2xke90sm/2/

只是Javascript:

    var localStorage = window.localStorage; 

            //First load all of the current notes in the user's storage into the page as list items
            var al1 = "";

            for(var p=0;p<localStorage.length;p++) {
                var temp  = localStorage.getItem(p.toString());
                if(temp != null) {              //assures that something is being written from memory, problem is that if it does find some null value, it's skipping over it
                    $("ul").append("<li id='note-" + p + "'><span>X</span> " + temp + "</li>");
                    al1 += "Note #" + p + ": '" + temp + "' has been loaded from memory. \n";
                } 
            }
            console.log(al1);

            // Check Off Specific Todos By Clicking
            $("ul").on("click", "li", function(){
                $(this).toggleClass("completed");

                //test if $("#note-[index]").html() is the same as localStorge.getItem(index.toString()) are the same.
                var matchingStorage = localStorage.getItem($(this).attr("id").slice(5).toString());
                console.log("HTML: " + $(this).text() + "\n" + "Local Storage: " + "X " + matchingStorage);
            });

            //Click on X to delete Todo
            $("ul").on("click", "span", function(event){
                $(this).parent().fadeOut(500,function(){
                    if(localStorage.getItem($(this).attr("id").slice(5).toString())) {
                        localStorage.removeItem($(this).attr("id").slice(5).toString());        //remove from storage
                        $(this).remove();       //remove from the page
                        reorder();
                    } else {
                        alert("could not delete element from storage.");
                    }
                });
                event.stopPropagation();
            });

            //Add new list item on enter key press
            $("input[type='text']").keypress(function(event){
                if(event.which === 13){
                    //grabbing new todo text from input
                    var todoText = $(this).val();
                    $(this).val("");
                    //create a new li, add to ul and give it the index of the localStorage system as the id
                    $("ul").append("<li id='note-" + localStorage.length + "'>" +  "<span>X</span> " + todoText + "</li>");
                    localStorage.setItem(localStorage.length.toString(), todoText);     //write the todoTextGet with the index as the key
                }
            });

            $("#toggle-form").click(function(){
                $("input[type='text']").fadeToggle();
            });

解决方案

这确实是可以用不同方式完成的任务,

优良作法是存储"项目,为它们提供唯一的标识符.

let localStorage;

function generateId() {
        let newId = Math.random().toString(36).substr(2);

        while (storageGet(newId)) {
            newId = Math.random().toString(36).substr(2);
        }
        return (newId);
}

function storageInsert(key, obj) {
    localStorage.setItem(key, obj);
}

function storageGet(key) {
    return (localStorage.getItem(key));
}

function storageRemove(key) {
    localStorage.removeItem(key);
}

$(document).ready(() => {
    localStorage = window.localStorage; 

    //Load all.
    for (let i = 0; i < localStorage.length; i++){
        let key = localStorage.key(i);
        $("ul").append("<li id='note-" + key +"'> <span>X</span> " + storageGet(key) + "</li>");
    }
});

//Click on X to delete Todo
$("ul").on("click", "span", function(event){
    $(this).parent().fadeOut(500,function(){
            storageRemove($(this).attr("id").substr(5).toString());
            $(this).remove();
    });
    event.stopPropagation();
});

//Add new list item on enter key press
$("input[type='text']").keypress(function(event){
    if(event.which === 13){
        //Hold input.
        let todoText = $(this).val();

        //Generate an unique ID.
        let newId = generateId();

        //Reset Input.
        $(this).val("");

        //Create new element.
        $("ul").append("<li id='note_" + newId + "'>" +  "<span>X</span> " + todoText + "</li>");

        //Add to storage.
        storageInsert(newId, todoText);
    }
});

$("#toggle-form").click(function(){
    $("input[type='text']").fadeToggle();
});

一个工作示例: https://jsfiddle.net/2xke90sm/38/

希望它对您有帮助!

AS more or less, a proof-of-concept I want to use the LocalStorage API to save list items into storage. The method that I came up with is a little complicated and inefficient but up to the deleting single list items use case, it's worked well. Here's how it roughly works. Using localStorage.length I use Javascript to give notes an "id". This way I can use a for loop to iterate over from the first note to localStorage.length and append each note to the HTML page during page load in between executions. Furthermore, with this id I can identify which note was clicked on with jQuery. The problem is with deleting notes. I can delete the note that the user clicked on, but if I don't reorder the list of notes that creates what they call "holes" in storage. So any ideas?

Live demo here, but maybe the localStorage API is not supported: https://jsfiddle.net/2xke90sm/2/

Just the Javascript:

    var localStorage = window.localStorage; 

            //First load all of the current notes in the user's storage into the page as list items
            var al1 = "";

            for(var p=0;p<localStorage.length;p++) {
                var temp  = localStorage.getItem(p.toString());
                if(temp != null) {              //assures that something is being written from memory, problem is that if it does find some null value, it's skipping over it
                    $("ul").append("<li id='note-" + p + "'><span>X</span> " + temp + "</li>");
                    al1 += "Note #" + p + ": '" + temp + "' has been loaded from memory. \n";
                } 
            }
            console.log(al1);

            // Check Off Specific Todos By Clicking
            $("ul").on("click", "li", function(){
                $(this).toggleClass("completed");

                //test if $("#note-[index]").html() is the same as localStorge.getItem(index.toString()) are the same.
                var matchingStorage = localStorage.getItem($(this).attr("id").slice(5).toString());
                console.log("HTML: " + $(this).text() + "\n" + "Local Storage: " + "X " + matchingStorage);
            });

            //Click on X to delete Todo
            $("ul").on("click", "span", function(event){
                $(this).parent().fadeOut(500,function(){
                    if(localStorage.getItem($(this).attr("id").slice(5).toString())) {
                        localStorage.removeItem($(this).attr("id").slice(5).toString());        //remove from storage
                        $(this).remove();       //remove from the page
                        reorder();
                    } else {
                        alert("could not delete element from storage.");
                    }
                });
                event.stopPropagation();
            });

            //Add new list item on enter key press
            $("input[type='text']").keypress(function(event){
                if(event.which === 13){
                    //grabbing new todo text from input
                    var todoText = $(this).val();
                    $(this).val("");
                    //create a new li, add to ul and give it the index of the localStorage system as the id
                    $("ul").append("<li id='note-" + localStorage.length + "'>" +  "<span>X</span> " + todoText + "</li>");
                    localStorage.setItem(localStorage.length.toString(), todoText);     //write the todoTextGet with the index as the key
                }
            });

            $("#toggle-form").click(function(){
                $("input[type='text']").fadeToggle();
            });

解决方案

This is indeed a task that can be done in different ways,

It is a good practice to 'store' items giving them a unique identifier.

let localStorage;

function generateId() {
        let newId = Math.random().toString(36).substr(2);

        while (storageGet(newId)) {
            newId = Math.random().toString(36).substr(2);
        }
        return (newId);
}

function storageInsert(key, obj) {
    localStorage.setItem(key, obj);
}

function storageGet(key) {
    return (localStorage.getItem(key));
}

function storageRemove(key) {
    localStorage.removeItem(key);
}

$(document).ready(() => {
    localStorage = window.localStorage; 

    //Load all.
    for (let i = 0; i < localStorage.length; i++){
        let key = localStorage.key(i);
        $("ul").append("<li id='note-" + key +"'> <span>X</span> " + storageGet(key) + "</li>");
    }
});

//Click on X to delete Todo
$("ul").on("click", "span", function(event){
    $(this).parent().fadeOut(500,function(){
            storageRemove($(this).attr("id").substr(5).toString());
            $(this).remove();
    });
    event.stopPropagation();
});

//Add new list item on enter key press
$("input[type='text']").keypress(function(event){
    if(event.which === 13){
        //Hold input.
        let todoText = $(this).val();

        //Generate an unique ID.
        let newId = generateId();

        //Reset Input.
        $(this).val("");

        //Create new element.
        $("ul").append("<li id='note_" + newId + "'>" +  "<span>X</span> " + todoText + "</li>");

        //Add to storage.
        storageInsert(newId, todoText);
    }
});

$("#toggle-form").click(function(){
    $("input[type='text']").fadeToggle();
});

A working example : https://jsfiddle.net/2xke90sm/38/

Hope it helps you!

这篇关于Web-使用LocalStorage API和jQuery删除选定的列表项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆