删除用户输入时出现问题

时间:2015-06-01 10:26:59

标签: javascript html arrays html5 local-storage

我正在尝试创建一个保存到本地存储的数组,用户可以对项目进行排序,添加项目,删除项目以及清除本地存储。我在删除或拼接用户输入工作时遇到很多麻烦,有人可以请我提供一些建议。

这是我到目前为止的代码,请原谅我,如果它不好,肯定知道如何做得更好。

...
<script>
    //lets my program know the books1 variable is an array
    var books1 = []
    //lets my program know the result variable is a string
    var result = ""
    //checks to see if the localstorage key booksArray exists, if it doesn't books1 has 3 books added ans is stored locally with a key of booksArray
    if (localStorage.getItem("booksArray") == null) {
        books1 = ["book1", "book2", "book3", "m", "p"]
        localStorage.setItem("booksArray", JSON.stringify(books1))
        // var theArray = JSON.parse("booksArray")
    }

    else {
        loadBooks(); //loads the books to an array with variable name listBooks
    }

    function loadBooks() {
        var result = localStorage.getItem("booksArray")
        var listBooks = JSON.parse(result)
    }



    function sortBooks() {
        var sortedBooks1 = localStorage.getItem("booksArray")
        var sortedBooks2 = JSON.parse(sortedBooks1)
        // loadBooks may work but haven't got it to yet. try redoing the project on books Array 2.2
        sortedBooks2.sort()
        document.getElementById("display1").innerHTML = sortedBooks2
        localStorage.setItem("booksArray",JSON.stringify(sortedBooks2))
    }

    function addBook() {
        var test1 = localStorage.getItem("booksArray")
        var addedBook = document.getElementById("inputData").value
        var addedBook2 = JSON.parse(test1)
        addedBook2.push(addedBook)
        document.getElementById("display1").innerHTML = addedBook2
        localStorage.setItem("booksArray", JSON.stringify(addedBook2))


    }

    function delBook() {
        //if (document.getElementById("inputData").value.length > 0) {
        var local = localStorage.getItem("booksArray")
        var delItem = document.getElementById("inputData").value
        var array = JSON.parse(local)
        var x = array.indexof(delItem);

        //test2.splice(delItem,1)
        if (delItem != -1) {
            delete booksArray[delItem]
        }
        document.getElementById("display1").innerHTML = test2
        }


    //     my test function    
    /*     function displaybooks() {
        var test1 = localStorage.getItem("booksArray")
        var test2 = JSON.parse(test1)
        document.getElementById("display1").innerHTML = test2[2]

    }
    */

    function clearLocal() {
        localStorage.clear()
    }
</script>
...

<body>
<!--i need to make the page so onload it displays the books--->
<form>
    <input type="text" id="inputData" />
</form>
<input type="button" onclick="delBook()" value="delete your books" />
<input type="button" onclick="sortBooks()" value="test me" />
<input type="button" onclick="addBook()" value="add your book" />
<input type="button" onclick="clearLocal()" value="clear local storage" />

<p id="display1"></p>
</body>
</html>

3 个答案:

答案 0 :(得分:1)

您可以为JSON数据的CRUD操作尝试此代码

$(function(){
    var operation = "A"; //"A"=Adding; "E"=Editing

    var selected_index = -1; //Index of the selected list item

    var tbClients = localStorage.getItem("tbClients");//Retrieve the stored data

    tbClients = JSON.parse(tbClients); //Converts string to object

    if(tbClients == null) //If there is no data, initialize an empty array
        tbClients = [];

    function Add(){
        var client = JSON.stringify({
            ID    : $("#txtID").val(),
            Name  : $("#txtName").val(),
            Phone : $("#txtPhone").val(),
            Email : $("#txtEmail").val()
        });
        tbClients.push(client);
        localStorage.setItem("tbClients", JSON.stringify(tbClients));
        alert("The data was saved.");
        return true;
    }

    function Edit(){
        tbClients[selected_index] = JSON.stringify({
                ID    : $("#txtID").val(),
                Name  : $("#txtName").val(),
                Phone : $("#txtPhone").val(),
                Email : $("#txtEmail").val()
            });//Alter the selected item on the table
        localStorage.setItem("tbClients", JSON.stringify(tbClients));
        alert("The data was edited.")
        operation = "A"; //Return to default value
        return true;
    }

    function Delete(){
        tbClients.splice(selected_index, 1);
        localStorage.setItem("tbClients", JSON.stringify(tbClients));
        alert("Client deleted.");
    }

    function List(){        
        $("#tblList").html("");
        $("#tblList").html(
            "<thead>"+
            "   <tr>"+
            "   <th></th>"+
            "   <th>ID</th>"+
            "   <th>Name</th>"+
            "   <th>Phone</th>"+
            "   <th>Email</th>"+
            "   </tr>"+
            "</thead>"+
            "<tbody>"+
            "</tbody>"
            );
        for(var i in tbClients){
            var cli = JSON.parse(tbClients[i]);
            $("#tblList tbody").append("<tr>"+
                                         "  <td><img src='edit.png' alt='Edit"+i+"' class='btnEdit'/><img src='delete.png' alt='Delete"+i+"' class='btnDelete'/></td>" + 
                                         "  <td>"+cli.ID+"</td>" + 
                                         "  <td>"+cli.Name+"</td>" + 
                                         "  <td>"+cli.Phone+"</td>" + 
                                         "  <td>"+cli.Email+"</td>" + 
                                         "</tr>");
        }
    }

    $("#frmCadastre").bind("submit",function(){     
        if(operation == "A")
            return Add();
        else
            return Edit();
    });

    List();

    $(".btnEdit").bind("click", function(){

        operation = "E";
        selected_index = parseInt($(this).attr("alt").replace("Edit", ""));

        var cli = JSON.parse(tbClients[selected_index]);
        $("#txtID").val(cli.ID);
        $("#txtName").val(cli.Name);
        $("#txtPhone").val(cli.Phone);
        $("#txtEmail").val(cli.Email);
        $("#txtID").attr("readonly","readonly");
        $("#txtName").focus();
    });

    $(".btnDelete").bind("click", function(){
        selected_index = parseInt($(this).attr("alt").replace("Delete", ""));
        Delete();
        List();
    });
});
body{
    font-family:Tahoma;
}

ul{
    list-style:none;
}

ul label{
    width:100px;
    float:left;
}

#frmCadastre{
    border:solid 1px;
}

#tblList{
    width:100%;
    border:solid 1px;
    text-align:left;
    border-collapse:collapse; 
}

#tblList tbody tr{
    border:solid 1px;
    height:30px;
}

#tblList thead{
    background:beige;
}
<html>
<head>
    <meta http-equiv="Content-Type" content="text/html;charset=utf-8" />
    <script type="text/javascript" src="http://code.jquery.com/jquery-1.8.3.min.js"></script>
</head>
<body>
    <form id="frmCadastre">
        <ul>
            <li>
                <label for="txtID">ID:</label>
                <input type="text" id="txtID"/>
            </li>
            <li>
                <label for="txtName">Name:</label>
                <input type="text" id="txtName"/>
            </li>
            <li>
                <label for="txtPhone">Phone:</label>
                <input type="text" id="txtPhone"/>
            </li>
            <li>
                <label for="txtEmail">Email:</label>
                <input type="text" id="txtEmail"/>
            </li>
            <li>
                <input type="submit" value="Save" id="btnSave"/>
            </li>
        </ul>
    </form>

    <table id="tblList">

    </table>
</body>
</html>

答案 1 :(得分:0)

尝试使用此clearLocal方法并在indexOf中更改(更正)

   function delBook() {  
         var x = array.**indexOf**(delItem);
   }


function clearLocal() {
      localStorage.clear()
      document.getElementById("display1").innerHTML = "";       
}

答案 2 :(得分:0)

本地存储API包含一个删除单个项目的方法:removeItem(key)。所以要删除你想要做的delItem:

localStorage.removeItem(delItem);