我正在关注this documentation并使用它下载数据并将其应用到 DOM。但是,我似乎无法应用它,因为我得到:
this.html is not a function: this.html(ajax_load);
代码:
(function( $ ){
$.fn.tasks = function() {
// there's no need to do $(this) because
// "this" is already a jquery object
// $(this) would be the same as $($('#element'));
$.ajax({
url: "include/tasks_handler.php?action=gettasks&list=default",
beforeSend: function() {
this.html(ajax_load);
},
success: function(html){
this.html(html);
}
});
};
})( jQuery );
$("#taskList").tasks();
我还尝试过 $(this),它可以阻止它崩溃,但它不会将内容注入(inject)到选择器中。
想法?
最佳答案
ajax 选项中的
this
指的是选项对象,而不是插件的上下文。解决方法是:
var that = this;
$.ajax({
url: "include/tasks_handler.php?action=gettasks&list=default",
beforeSend: function() {
that.html(ajax_load);
},
success: function(html){
that.html(html);
}
});
这个简单的示例演示了正在发生的事情:
var obj = {
foo: function() {
alert("bar");
},
bar: function() {
alert(this.foo);
}
};
obj.bar(); // function() { alert("bar"); }
这个例子更好地演示了正在发生的事情:
var options = {
success: function(html) {
this.html(html);
},
html: function(html) {
alert("This is not the .html() you are looking for, move along." + html);
}
}
options.success("some html");
fiddle :http://jsfiddle.net/GTScL/
关于jquery-plugins - 创建 jquery 插件 : this. html 不是函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6975279/