gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 23:50:03 24 4
gpt4 key购买 nike

以下代码从文件加载 html 内容(我使用 this thread )

<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 没有您期望的值。

但是,您确实可以在 loadWithoutCache 本身内访问 this(具有预期值)。因此,您可以通过将 $(this) 保存到局部变量中并从成功处理程序内部访问它(创建闭包)来实现您的目标。

这是您需要做的:

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

关于jquery - $(this) 在函数中不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7859558/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com