开发者

jquery ajax events with classes

I have this code:

$('.be-delete').live('click', function(e){
    e.preventDefault();
    var object =$(this);
    var url = $(this).attr('href');
    $.ajax({
        url : url,
        error : function(){alert('An error has occurred, no updates were made')},
        success : function(){
            object.parent().fadeOut('slow', function(){object.parent().remove()});
        }
    });
});

$('.be-delete').ajaxStart(function(){
    $(this).parent().html('<img src="' + base_url + 'media/images/jquery/spinner.gif' + '"/>');
});

the prob开发者_如何学Pythonlem is $(this) on the ajaxStart callback is not working and all li's are affected! my html markup is as follows:

<li><img src="1.jpg"/><a class="be-delete"href="#">Delete</a></li>
<li><img src="2.jpg"/><a class="be-delete"href="#">Delete</a></li>
<li><img src="3.jpg"/><a class="be-delete"href="#">Delete</a></li>

how do I capture the ajaxStart event for only one li?


You could do something like this. This sets a data attribute on the clicked element. Thus you can identify in ajaxStart which li really was clicked.

$('.be-delete').live('click', function(e){
    e.preventDefault();
    var object =$(this);
    object.data("clicked", "yes");
    ...
});

$('.be-delete').ajaxStart(function(e) {
    var ele = $(e.target);
    if(ele.data("clicked")=="yes") {
        ele.removeData("clicked");
        ele.parent().html('<img src="' + base_url + 'media/images/jquery/spinner.gif' + '"/>');
    }
});

Btw. just as a note. You should do this a bit differently. As in the ajaxStart you set the innerHTML of the parent div to show the spinner. But what are you going to do when the ajax request fails? The original content of the li is lost and the li will still display but now only showing the spinner instead of the original content.


ajaxStart is a broadcast event sent to all items subscribing to it. i think your best bet is to record in a global the element that was clicked, and then in the ajaxStart handler perform your img swap using that object alone, not the element(s) receiving the start event

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜