日期:2014-05-16  浏览次数:20290 次

jquery动态删除问题
一个函数首先是ajax到php后台把数据库中对应的记录删除,然后返回模板页面一个表示成功删除的值(msg==1),此时模板页面使用jquery移除对应的dom,
$('.del').live('click',function(){
  var id = $(this).next().val();
  if(id == '' || id == null){
  $(this).parent().parent().remove();  
  }else{
  confirmnew('确定要删除该商品吗?',function(){  
  $.get('__APP__/BygCom/delPF',{rand:Math.random(),fpid:id},function(msg){
  if(msg == 1){
  $(this).parent().parent().remove();
  }else{
  alert('删除失败!');
  }
  });
  });
  }
});
红色部分是不能运行的代码,我有试着在if(msg==1)中alert('test');能够打印出test,而且数据库中的记录也是被删除了的。
删除按钮的表格结构:
<tr>
  <td>
  <input type='button' class='del' />
  </td>
</tr>

------解决方案--------------------

var self = $(this);
confirmnew('确定要删除该商品吗?',function(){
$.get('__APP__/BygCom/delPF',{rand:Math.random(),fpid:id},function(msg){
if(msg == 1){
self.parent().parent().remove();
}else{
alert('删除失败!');
}
});
});
}
------解决方案--------------------
你在回调函数里面使用this,当前this并不是$('.del')对象。不出意外的话应该是window对象。
------解决方案--------------------
红色的那个this是在function(msg)里面的

改成:

$('.del').live('click',function(){
  var that = this;
var id = $(this).next().val();
if(id == '' || id == null){
$(this).parent().parent().remove();
}else{
confirmnew('确定要删除该商品吗?',function(){
$.get('__APP__/BygCom/delPF',{rand:Math.random(),fpid:id},function(msg){
if(msg == 1){
$(that).parent().parent().remove();
}else{
alert('删除失败!');
}
});
});
}
});