2009-12-29 256 views
1

嗨具有以下功能的正常工作:传递对象使用jQuery

 jQuery('.btnRemoveItem').click(function(obj){     
      jQuery(this).closest('li').fadeOut(400, function() { $(this).remove(); }); // This works 
     }); 

在此HTML代码:

<li id="listItem_dsc_6440.jpg"> 
    <div class="buttonPanel"> 
     <span title="Delete image" class="btnRemoveItem floatRight" id="dsc_6440.jpg"> </span> 
    </div> 
</li> 

这变淡下列表项,然后删除它。
现在我加入了jQuery.post,我需要把淡出/删除这里面.POST

 jQuery('.btnRemoveItem').click(function(obj){ 

      jQuery.post("wp-content/themes/storelocator/include/adm_gallery.php", { deleteImage: 'single', name: jQuery(this).attr('id') }, 
      function(data){ 
       if(data.status == 'deleted'); 
       { 
        jQuery(obj).closest('li').fadeOut(400, function() { $(this).remove(); }); 
       } 
      }, "json"); 
     }); 

当然,这是行不通的。我很确定这是因为我不知道obj是什么 - 以及我如何使用它。

任何人都可以帮助我吗?

回答

1

this保存在局部变量中。像这样:

jQuery('.btnRemoveItem').click(function(){ 
     var obj = this; //reference to the button 
     jQuery.post("wp-content/themes/storelocator/include/adm_gallery.php", { deleteImage: 'single', name: jQuery(this).attr('id') }, 
     function(data){ 
      if(data.status == 'deleted'); 
      { 
       jQuery(obj).closest('li').fadeOut(400, function() { $(obj).remove(); }); 
      } 
     }, "json"); 
    }); 

post的回调函数形成一个闭包,它可以'看到'外层函数的局部变量。

+0

Thos很棒。谢谢! – Steven

0

解决此问题的一种简单方法是在返回JSON响应时使您的“删除”页面返回已删除对象的ID /其他标识属性。然后,您只需执行jQuery('#' + data.object_id)即可找到需要删除的对象。

通常情况下,我使用像object-1,object-2等ID这样做 - 然后我的代码只是在检索HTML中的项目时寻找#object-[foo]进行修改。

0

由于您obj是你,然后点击按钮,我想你可以在第2个功能的东西取代jQuery(obj).closest('li')jQuery('.btnRemoveItem').closest('li')

+0

只有一个.btnRemoveItem元素存在时,您的解决方案才有效。如果给定的className有更多的元素,你的解决方案会影响所有的元素。 – Rafael

+0

我有大约15'.btnRemoveItem'; o) – Steven

+0

是的 - 如果有多个然后分配本地var到'this'将工作 – Bostone

0

请问,即使你删除的“后”的最后一个参数(这是这个错误发生目前是“json”)?有时,当返回类型与预期不同时,回调方法从不会被调用。

1

点击的第一个参数()方法是事件对象,因此可以使用所述目标属性

jQuery(obj.target).closest('li').fadeOut(...); 

或只是限定保持所述参考元件的点击处理程序内的辅助可变

jQuery('.btnRemoveItem').click(function(obj){ 
    var element = this; 

    jQuery.post(... 
     function(data){ 
     if(data.status == 'deleted'){ 
      jQuery(element).closest('li').fadeOut(...); 
     }, 
     }, 'json'); 
});