2014-01-26 136 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