passing on object using jQuery
Hi have the following function which works fine:
jQuery('.btnRemoveItem').click(function(obj){
jQuery(this).closest('li').fadeOut(400, function() { $(this).remove(); }); // This works
});
On this HTML code:
<li id="listI开发者_开发知识库tem_dsc_6440.jpg">
<div class="buttonPanel">
<span title="Delete image" class="btnRemoveItem floatRight" id="dsc_6440.jpg"> </span>
</div>
</li>
This fades down the list item, then removes it.
Now I'm adding ajQuery.post
and I need to put the fadeout / remove inside this .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");
});
Of course, this doesn't work. I'm pretty sure it's because I don't know what obj
is - and how I can use it.
Can anyone help me please?
Save this
in a local variable. Like 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");
});
The callback function of post forms a closure and it can 'see' the local variables of the outer function.
The first parameter of click() method is the event object, so you can use the target property
jQuery(obj.target).closest('li').fadeOut(...);
or just define a helper variable inside the click handler that holds the reference to the element
jQuery('.btnRemoveItem').click(function(obj){
var element = this;
jQuery.post(...
function(data){
if(data.status == 'deleted'){
jQuery(element).closest('li').fadeOut(...);
},
}, 'json');
});
An easy way to work around this would be to have your 'delete' page, when returning a JSON response, also return the ID/other identifying attribute for the object that was deleted. Then, you can just do jQuery('#' + data.object_id)
to find the object you need to remove.
Typically, I do this using IDs like object-1, object-2, etc. - and then my code just looks for #object-[foo]
when retrieving an item in the HTML to modify.
Since your obj
is the button you clicked at then I suppose you can replace jQuery(obj).closest('li')
in the 2nd function with something like jQuery('.btnRemoveItem').closest('li')
Does this error occur even when you remove the last parameter of "post" (which is currently "json")? Sometimes, when return type is different than the expected, the callback method is never called.
精彩评论