jQuery:在$ .ajax成功函数中使用$(this)

时间:2022-02-21 19:05:55

I'm making an $.ajax call, and the following code does not work as intended. The alert results in 'undefined'

我正在进行$ .ajax调用,以下代码无法正常工作。警报导致'undefined'

$(document).ready( function {
  $(".elem").on("click", function(e) {

    e.preventDefault();

    $.ajax( {
      url: 'index.php',
      data: {
        'action': 'something'
      },
      success: function() {
        alert($(this).data("foobar"));
      }
    });
  });
)};

However, I was able to get it working by adding an alias to $(this) before entering the ajax function.

但是,在进入ajax函数之前,我能够通过在$(this)中添加别名来实现它。

$(document).ready( function {
  $(".elem").on("click", function(e) {

    var old_this = $(this);

    e.preventDefault();

    $.ajax( {
      url: 'index.php',
      data: {
        'action': 'something'
      },
      success: function() {
        alert(old_this.data("foobar"));
      }
    });
  });
)};

I can't assign unique IDs to the element being clicked, so accessing it via $("#id") isn't an option.

我无法为被单击的元素分配唯一ID,因此通过$(“#id”)访问它不是一个选项。

Is there a more standardized approach to accessing the $(this) that existed before entering the success function or does this way work just fine?

是否有更标准化的方法来访问在进入成功函数之前存在的$(this),或者这种方式是否正常工作?

1 个解决方案

#1


6  

The way that you have it is just fine. By default this in jQuery ajax callbacks is the ajax settings object (you can set via $.ajaxSettings). $.ajax also has a context property that you can set:

你拥有它的方式就好了。默认情况下,这在jQuery ajax回调中是ajax设置对象(您可以通过$ .ajaxSettings设置)。 $ .ajax还有一个可以设置的上下文属性:

$.ajax({
    url: url,
    data: data,
    context: this,
    success: success
});

Then you could use $(this) as expected, but personally I find the reassignment of this easier to understand. You may want to pick a better variable name than old_this, though.

然后你可以按预期使用$(this),但我个人觉得这种重新分配更容易理解。但是,您可能希望选择比old_this更好的变量名称。

#1


6  

The way that you have it is just fine. By default this in jQuery ajax callbacks is the ajax settings object (you can set via $.ajaxSettings). $.ajax also has a context property that you can set:

你拥有它的方式就好了。默认情况下,这在jQuery ajax回调中是ajax设置对象(您可以通过$ .ajaxSettings设置)。 $ .ajax还有一个可以设置的上下文属性:

$.ajax({
    url: url,
    data: data,
    context: this,
    success: success
});

Then you could use $(this) as expected, but personally I find the reassignment of this easier to understand. You may want to pick a better variable name than old_this, though.

然后你可以按预期使用$(this),但我个人觉得这种重新分配更容易理解。但是,您可能希望选择比old_this更好的变量名称。