$(this) doesn't work in a function

前端 未结 5 1808
渐次进展
渐次进展 2020-11-30 14:44

The following code loads html content from a file (i used this thread)



        
5条回答
  •  清歌不尽
    2020-11-30 15:00

    The problem is that inside the success callback, this does not have the value you expect it to.

    However, you do have access to this (with the expected value) inside loadWithoutCache itself. So you can achieve your goal by saving $(this) into a local variable and accessing it from inside the success handler (creating a closure).

    This is what you need to do:

    $.fn.loadWithoutCache = function (){
     var $el = $(this);
     $.ajax({
         url: arguments[0],
         cache: false,
         dataType: "html",
         success: function(data) {
            $el.html(data);
            alert(data);
        }
     });
    }
    

提交回复
热议问题