使用jQuery传递对象
Hi具有以下功能,工作正常:使用jQuery传递对象,jquery,Jquery,Hi具有以下功能,工作正常: jQuery('.btnRemoveItem').click(function(obj){ jQuery(this).closest('li').fadeOut(400, function() { $(this).remove(); }); // This works }); 关于此HTML代码: <li id="listItem_dsc_6440.jpg">
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>
当然,这是行不通的。我很确定这是因为我不知道什么是obj,也不知道如何使用它
有人能帮我吗?解决这一问题的一个简单方法是让您的“删除”页面在返回JSON响应时,还返回已删除对象的ID/其他标识属性。然后,只需执行
jQuery(“#”+data.object\u id)
即可找到需要删除的对象
通常,我使用object-1、object-2等ID执行此操作,然后在检索HTML中要修改的项时,我的代码只查找
\object-[foo]
。将保存在局部变量中。像这样:
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的回调函数形成了一个闭包,它可以“看到”外部函数的局部变量。因为您的obj
是您单击的按钮,所以我想您可以将第二个函数中的jQuery(obj).latest('li')
替换为类似于jQuery('btnremovitem').latest('li'))
即使删除“post”(当前为“json”)的最后一个参数,也会发生此错误吗?有时,当返回类型与预期不同时,将永远不会调用回调方法。click()方法的第一个参数是事件对象,因此可以使用target属性
jQuery(obj.target).closest('li').fadeOut(...);
或者在保存元素引用的click处理程序中定义一个helper变量
jQuery('.btnRemoveItem').click(function(obj){
var element = this;
jQuery.post(...
function(data){
if(data.status == 'deleted'){
jQuery(element).closest('li').fadeOut(...);
},
}, 'json');
});
当只有一个.btnRemoveItem元素存在时,您的解决方案将起作用。如果有更多具有给定类名的元素,您的解决方案将影响所有元素。我有大约15个.btnRemoveItem
;o) 是-如果有多个,则将本地var分配给,这将起作用
jQuery('.btnRemoveItem').click(function(obj){
var element = this;
jQuery.post(...
function(data){
if(data.status == 'deleted'){
jQuery(element).closest('li').fadeOut(...);
},
}, 'json');
});