jquery-plugins - 创建 jquery 插件 : this. html 不是函数

标签 jquery-plugins jquery jquery-selectors

我正在关注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/

相关文章:

jquery - jCarousel:您可以删除所有项目并重新绑定(bind)到新集合吗?

jquery-plugins - jQuery Plugin 方法不是函数 - Webpack、VS2017、ASP.NET Core 2.0

javascript - floatThead 和 bootstrap downdrop

javascript - 如何根据 ID、使用 javascript、点击按钮加载不同的 YouTube 视频?

javascript - 向下或向上滚动时如何显示或隐藏菜单?

jquery - knockout 中的复选框绑定(bind)不适用于触发事件

javascript - 使用正则表达式选择元素 jQuery

jquery - jQuery 选择器可以选择具有 "onclick"属性的所有元素吗?

javascript - 如何使用 jOrgChart 在 HTML 文件中创建图表?

jquery - 有哪些关于使用 jQuery 和/或 HTML 构建游戏的优秀教程?