Mir*_*iro 4 ajax jquery load this
以下代码从文件加载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>
Run Code Online (Sandbox Code Playgroud)
请告诉我这是什么问题?我希望这是一个愚蠢的东西:)
编辑:正确的代码
<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>
Run Code Online (Sandbox Code Playgroud)
谢谢乔恩和大家!
问题是成功回调内部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);
}
});
}
Run Code Online (Sandbox Code Playgroud)