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

2024-04-20

以下代码从文件加载 html 内容(我使用这个线程 https://stackoverflow.com/questions/168963/stop-jquery-load-response-from-being-cached)

<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>

谢谢乔恩和大家!


问题是在成功回调中,this没有您期望的价值。

但是,您确实可以访问this(与预期值)里面loadWithoutCache本身。这样您就可以通过储蓄来实现您的目标$(this)放入局部变量并从成功处理程序内部访问它(创建闭包)。

这是你需要做的:

$.fn.loadWithoutCache = function (){
 var $el = $(this);
 $.ajax({
     url: arguments[0],
     cache: false,
     dataType: "html",
     success: function(data) {
        $el.html(data);
        alert(data);
    }
 });
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

$(this) 在函数中不起作用 的相关文章

随机推荐