编辑后在jquery mobile中重新加载页面

时间:2014-01-03 15:40:54

标签: javascript jquery-mobile mobile web-applications

你好我已经完成了一个使用phonegap的Android应用程序,现在我正在尝试更改webapp的代码(应用程序只是一个笔记保存),但我有一个问题,当更改页面,编辑后注意应用程序返回到索引页面,当您单击注释以查看单个注释时,应用程序将再次显示索引页面(如果再次单击,则会发生一次,工作正常)

样本 notesapp

这是js代码的一部分

 editNote: function(e){
        var noteId = $("#id-note").attr("value");
        var newText = $.trim($("#textarea-edit").val());
        var storage = window.localStorage.getItem("notes");
        storage = JSON.parse(storage);
        var newStorage = [];


        for( obj in storage ){
            if(noteId == storage[obj].id){
                newStorage.push({
                    id: storage[obj].id,
                    text: newText,
                    created: storage[obj].created 
                });
            }else{
                newStorage.push(storage[obj])
            }
        }

        window.localStorage.setItem("notes", JSON.stringify(newStorage));
        notes.showNotes();
        $.mobile.changePage($('#index'));


    }

$(document).bind("pagebeforechange", function(e, data){
    var u = $.mobile.path.parseUrl( data.toPage )
    if(u.hash){
        var page = u.hash.split("?")[0],
            idNote = u.hash.split("=")[1],
            storage = window.localStorage.getItem("notes"),
            singleText
        ;

        storage = JSON.parse(storage);

        // GET CURRENT NOTE TEXT
        for( obj in storage ){
            if(idNote == storage[obj].id){
                singleText = storage[obj].text;
            }
        }

        // SET ID-NOTE TO A INPUT HIDE FOR LATER RETRIEVE
        $("#id-note").attr("value", idNote)

        if(page == "#single"){ 
            if(idNote){
                console.log("show single page")  

                $("#single-note").html(singleText);
                $("#editnote-button").attr("href","#editnote?id=" + idNote);
            }
        }else if(page == "#editnote"){
            console.log("Show edit")

            $("#textarea-edit").val(singleText);
        }

    }


  });

1 个答案:

答案 0 :(得分:1)

您的问题在于每当启动页面notes.init()时执行pageinit。根据您的代码,notes.init()会在下面的按钮中添加多个click侦听器。

$("#save-note").on("click", notes.saveNote);
$("#delete-note").on("click", notes.deleteNote);
$("#edit-note-button").on("click", notes.editNote);

要解决此问题,请将pageinit绑定到#index页面。这样notes.init()只运行一次。或者删除旧的click绑定并将其重新绑定到相同的按钮。

$("#save-note").off("click").on("click", notes.saveNote);
$("#delete-note").off("click").on("click", notes.deleteNote);
$("#edit-note-button").off("click").on("click", notes.editNote);

或仅运行一次pageinit

$(document).one("pageinit", function () {
  notes.init();
});