2014-01-26 137 views
0

我想做一個待辦事項列表類型的事情。 在這裏,我希望將新目標保存到數據庫,然後僅對具有相關列表的div進行刷新,並顯示添加了新目標的列表。

數據庫更新正常,新的列表項返回新的HTML就好了,但 .replaceWith()似乎不工作。什麼都沒發生。

它的工作原理是功能之外,而不是裏面的話,我不知道爲什麼。

$('.addGoal').submit(function(event){ 
    var listid = $(this).attr('id'); 
    var desc = $(this).children('.goalinput').val(); 

    event.preventDefault(); 

    if(desc == "") { 
     console.log("empty!"); 
     return; 
    } 

    var posting = $.post("updatedata.php", { what :'addgoal', id: listid, data: desc}); 
    posting.done(function(data){ 
      console.log("saved!" + data); //this works, the updated html is being returned 
      $(this).closest('#goallist').replaceWith("Returned data goes here"); //this works outside of this function but not inside of it. 
     }); 
    }); 

回答

2

this不會自動保留其在回調函數中的值。你需要一個閉包變量綁定:

$('.addGoal').submit(function(event){ 
    var listid = $(this).attr('id'); 
    var desc = $(this).children('.goalinput').val(); 

    event.preventDefault(); 

    if(desc == "") { 
     console.log("empty!"); 
     return; 
    } 

    var that = this; // Closure variable 
    var posting = $.post("updatedata.php", { what :'addgoal', id: listid, data: desc}); 
    posting.done(function(data){ 
     console.log("saved!" + data); 
     $(that).closest('#goallist').replaceWith("Returned data goes here"); 
    }); 
}); 
+0

而且由於ID必須是唯一的,所以使用'$('#goallist')。replaceWith(...)'。 – undefined

+0

確實如此,儘管在需要找到與此相關的元素的更一般的情況下它不起作用。 – Barmar

+0

是的,的確如此。 – undefined