×

jQuery ajax使用$(this).parent()无效解决方法

admin admin 发表于2016-02-18 22:55:52 浏览1818 评论0

抢沙发发表评论

本文章来给各位同学介绍一下关于jQuery ajax使用$(this).parent()无效解决方法,希望此方法对各位同学人有所帮助哦

html

 代码如下复制代码
<p class="item">
<input type="text" name="meta_key[164]" value="file1" size="20"  /><a href="/18" id="164" class="button remove">remove</a>
</p>

需求说明:
鼠标点击‘remove’链接,根据ajax的返回值删除页面元素。

无效的方法

 代码如下复制代码
$('.remove').bind('click',function(){
    
   $.ajax({
   type:'post',
   url:$(this).attr('href'),
   dataType : 'json',
   data:{id : $(this).attr('id')},
   success:function(msg){
      if(msg.error==0){
        alert(msg.msg);
     }else{
        $(this).parent().remove(); //此处无法获得父级元素
     }
     } 
    
    });
   return false;
   });

有效的方法

 代码如下复制代码
$('.remove').bind('click',function(){
   
   div=$(this).parent(); //先获取父级元素
   
   $.ajax({
   type:'post',
   url:$(this).attr('href'),
   dataType : 'json',
   data:{id : $(this).attr('id')},
   success:function(msg){
    if(msg.error==0){
     alert(msg.msg);
    }else{
      div.remove(); //再删除
    }
     } 
    
    });
   return false;
   });

其他类似问题也可以通过相同方法解决


分享到:

群贤毕至

访客