4

假设我有一堆共享点击事件的链接:

<a href="#" class="do-stuff">Click me</a>
<a href="#" class="do-stuff">Click me</a>
<a href="#" class="do-stuff">Click me</a>
<a href="#" class="do-stuff">Click me</a>

在 $('.do-stuff').click 函数中,我执行一个 JQuery ajax POST 请求,用东西更新数据库,我得到了成功的响应。ajax完成后,我只想将链接文本的值更改为我从服务器发回的任何内容......

$('.do-stuff').click(function () {
$.ajax({
  type: "POST",
  url: "MyWebService.asmx/DoSomething",
  data: '{CurrentLinkText: "'+ $(this).text() +'"}',
  contentType: "application/json; charset=utf-8",
  dataType: "json",
  success: function (result) {
    $(this).text(result.d);
  },
  error: function (XMLHttpRequest, textStatus, errorThrown) {
    alert(textStatus);
  }
});

});

这调用得很好,我验证了“result.d”确实是来自服务器的文本,但文本没有改变。我认为在 AJAX 发布之后不再可以访问 $(this) 元素?我能做些什么来解决这个问题?

4

5 回答 5

13

一般来说,当你失去这样的上下文时,你可以保存对对象的引用。像这样:

function clickHandler() {
    var that = this;
    $.ajax( { url: '#',
        success: function (result) {
            $(that).text(result.d);
        }
    );
}
于 2012-06-14T05:45:51.813 回答
4

请参阅此处: AJAX 成功中的 $(this) 不起作用

您可以设置上下文选项

该对象将成为所有与 Ajax 相关的回调的上下文。默认情况下,上下文是一个对象,表示调用中使用的 ajax 设置($.ajaxSettings 与传递给 $.ajax 的设置合并)。(...)

例子:

$.ajax({
    //...
    context: this,
    success: function(json) {
        //...
    }
});

或使用$.proxy

$.ajax({
    //...
    success: $.proxy(function(json) {
         //...
    }, this)
});
于 2012-06-14T05:46:35.853 回答
3

尝试:

success: $.proxy(function(result) {
         //...
    }, this)
于 2012-06-14T05:47:04.077 回答
1

There are lots of ways to do this, as you can see from the answers here. Personally, I prefer to construct a function bound to the current value of this:

success: (function(target) {
              return function(result) {
                   $(target).text(result.d);
              }
         })(this)

It's neat, clean, and $(this) will remain the same as it is in the outer context; i.e. it will be the element that raised the event.

于 2012-06-14T05:58:19.370 回答
0
jQuery('#youridvalue').html(result.d);
jQuery('.yourclassvalue').html(result.d);

用它

于 2012-06-14T05:48:03.340 回答