jQuery Ajax事件与类 [英] jquery ajax events with classes

查看:62
本文介绍了jQuery Ajax事件与类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有此代码:

$('.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' + '"/>');
});

问题是ajaxStart回调上的$(this)无法正常工作,所有li都将受到影响!我的html标记如下:

the problem 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>

我如何只捕获一个li的ajaxStart事件?

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

推荐答案

您可以执行以下操作.这将在clicked元素上设置一个data属性.因此,您可以在ajaxStart中确定真正点击了哪个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' + '"/>');
    }
});

顺便说一句.只是一个注释.您应该做一些不同的事情.与在ajaxStart中一样,您可以设置父div的innerHTML以显示微调器.但是,当ajax请求失败时,您将怎么办? li的原始内容丢失,并且li仍会显示,但现在仅显示微调框而不是原始内容.

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.

这篇关于jQuery Ajax事件与类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆