繁体   English   中英

jQuery拼接数组删除错误

[英]JQuery splice array deleting wrong

我正在用cordova制作混合应用程序,但有两个问题

  1. 当我双击列表中的一个项目时,它会删除正确的项目,但是当我关闭并重新打开该应用程序时,它将删除列表中的最后一个项目,因此,基本上,它会删除我在屏幕上双击的那个项目,但是在数组,它总是删除列表中的最后一项。

  2. 我无法从列表中删除刚刚添加的项目,我需要关闭并重新打开应用程序才能将其删除。

问题出现在底部功能

这是我的JavaScript文件(JQuery):

    var taskListArray = new Array();

    $(document).ready(function()
    {
        var addInput = $("#addInput");
        var taskList = $("#taskList");

        if(window.localStorage)
        {
            taskListArray = JSON.parse(window.localStorage.getItem("taskList"))
        }
        else
        {
            window.plugins.toast.showLongCenter("LocalStorage not found, saving unavailable!");
        }

        if(taskListArray != null)
        {
            for(i = 0; i < taskListArray.length; i++)
            {
                var task = "<li>" + taskListArray[i].task + "</li>";
                taskList.append(task);
            }
        }
        else
        {
            taskListArray = new Array();
        }

        $("#addButton").on("click", function()
        {
            if($("#addInput").val() != 0)
            {
                var task = "<li>" + addInput.val() + "</li>";
                taskList.append(task);
                taskListArray.push({task:addInput.val()});

                if(window.localStorage)
                {
                    window.localStorage.setItem("taskList", JSON.stringify(taskListArray));
                }

                addInput.val("");
                window.plugins.toast.showShortCenter("Task added!");
            }
        });

        $("li").dblclick(function()
        {
            //Removes last task instead of the task I double tapped on
            //and I can't remove newly added tasks
            taskListArray.splice($.inArray($(this), taskListArray), 1);

            $(this).remove();
            window.plugins.toast.showShortCenter("Task removed!");

            if(window.localStorage)
            {
                window.localStorage.setItem("taskList", JSON.stringify(taskListArray));
            }
        });
    });

编辑:对问题2仍然没有答案? 非常感谢您对两个问题的回答,或者至少一个,谢谢!

$.inArray需要两个参数,但是您只传递了一个。 仅带有一个参数的函数将返回-1,并且在参数为-1时, splice函数将删除最后一个元素。 它应该像这个taskListArray.splice($.inArray($(this), taskListArray), 1); jQuery inArray文档

您能否替换代码taskListArray.splice($。inArray($(this)),1); 与taskListArray.splice($。inArray($(this),taskListArray),1); 并尝试。

在jQuery文档中,它指出您需要提供您需要在其中搜索的数组。

jQuery.inArray(value,array [,fromIndex])

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM