【问题标题】:after jquery ajax sucess $(this) not working在 jquery ajax 成功后 $(this) 不工作
【发布时间】:2014-08-02 06:48:15
【问题描述】:

我是 js 和 jquery 新手,请帮我解决这个问题, 问题是:

$(this).html('<span class="label label-success icon-fontawesome-webfont-11"> Paid</span>');

不工作。

window.onload = function() {
    $(".myclass").click(function(){
        var current_id = this.id;
            $.ajax({
                type: "POST",
                url: "/ajax.php",
                data:'current_id='+ current_id
           }).done(function(result) {
                $(this).html('<span class="label label-success icon-fontawesome-webfont-11"> Paid</span>');
          });
    });
}

【问题讨论】:

  • 请格式化您的代码..!
  • 当你点击只是检查检索数据是否有任何错误?查看检查元素中的错误
  • 检索数据没有错误。

标签: jquery ajax this innerhtml


【解决方案1】:

您可以使用$.proxy 来修复它。

$(".myclass").click(function(){

    var current_id = this.id;
        $.ajax({

            type: "POST",

            url: "/ajax.php",

            data:'current_id='+ current_id

       }).done($.proxy(function(result) {
            $(this).html('<span class="label label-success icon-fontawesome-webfont-11"> Paid</span>');
      }, this));  

});

【讨论】:

  • 酷,我以前没见过!非常方便。
【解决方案2】:

尝试添加context,例如:

window.onload = function() {
    $(".myclass").click(function(){
        var current_id = this.id;
            $.ajax({
                type: "POST",
                context: this, //add this
                url: "/ajax.php",
                data:{current_id : current_id},
           }).done(function(result) {
                $(this).html('<span class="label label-success icon-fontawesome-webfont-11"> Paid</span>');
          });
    });
}

【讨论】:

  • 你能解释一下为什么在这个特定的代码中需要上下文
  • @alagu 如果您自己保留上下文,则不是。 jQuery 在调用处理程序时重新定义了 this
  • this in dont context 是一个代表 ajax 设置的对象,所以使用 context: this,会将 context 作为您的 dom 对象,请参阅答案中链接的文档
  • 感谢您的详细解释@Brad
【解决方案3】:

this 的上下文发生变化。在这种情况下,this 上下文绑定到 Deferred done 处理程序的结果。在您的点击函数中,将this 的值存储在一个变量中。然后,稍后访问它。

$(".myclass").click(function(){
    var current_id = this.id;
    var $clicked = $(this);
    $.ajax({
        type: "POST",
        url: "/ajax.php",
        data:'current_id='+ current_id
    ).done(function(result) {
        $clicked.html('<span class="label label-success icon-fontawesome-webfont-11"> Paid</span>');
    });
});

另外,我不知道你为什么要按你的方式指定数据,但考虑只使用一个对象,让 jQuery 来完成这项工作。 data: {current_id: current_id}。否则,您将不得不自己对值进行编码。

【讨论】:

  • 谢谢,回复我只是用谷歌搜索它并在我的代码中使用仍然面临问题
  • 那么如何发送,多个数据@brad
  • @alagu 只需添加到对象{key1: 'value1', key2: 'value2'}。我建议在继续之前阅读 JavaScript。对象字面量是语法的关键部分。
猜你喜欢
  • 1970-01-01
  • 2019-11-28
  • 1970-01-01
  • 2011-09-17
  • 2011-06-26
  • 2012-05-20
  • 1970-01-01
  • 2014-01-31
  • 1970-01-01
相关资源
最近更新 更多