小编典典

$(this)在函数中不起作用

ajax

以下代码从文件加载html内容我使用了该线程

<script>
$.fn.loadWithoutCache = function (){
 $.ajax({
     url: arguments[0],
     cache: false,
     dataType: "html",
    success: function(data) {
        $(this).html(data);        // This is not working
      //$('#result').html(data);   //THIS WORKS!!!
        alert(data);           // This alerts the contents of page.html
    }
 });
}


$('#result').loadWithoutCache('page.html');

</script>

请让我知道问题是什么?我希望这是愚蠢的:)

编辑:正确的代码

<script>
$(document).ready(function() {

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

$('#result').loadWithoutCache('page.html');

});
</scipt>

谢谢乔恩和大家!


阅读 396

收藏
2020-07-26

共1个答案

小编典典

callback(success)函数在响应到达时运行,并且不在loadWithoutCache方法范围内运行,因为该函数已经结束。

您可以contextajax调用中使用属性来设置回调函数的上下文:

$.fn.loadWithoutCache = function (){
  $.ajax({
    url: arguments[0],
    cache: false,
    dataType: "html",
    context: this,
    success: function(data) {
      $(this).html(data);
    }
  });
}
2020-07-26