【问题标题】:creating a jquery plugin: this.html is not a function创建一个 jquery 插件:this.html 不是一个函数
【发布时间】:2011-10-21 23:05:31
【问题描述】:

我正在关注this documentation 并使用它来下载数据并将其应用到 DOM。但是,我似乎无法应用它:

this.html 不是函数: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),它可以阻止它破坏,但它不会将内容注入选择器。

想法?

【问题讨论】:

  • 使用$(this) 使其成为具有.html 方法的jQuery 对象。发布 then 发生的事情作为问题(因为那是实际问题:)
  • @FLX:你想用this 指代什么?
  • 另外,this 在 beforeSend 的回调范围内不可用。您必须执行 var somevar = this; 才能使其在回调中可见——有趣的 this 范围规则。

标签: jquery-plugins jquery jquery-selectors


【解决方案1】:
ajax 选项中的

this 指的是 options 对象,而不是插件的上下文。解决方法是:

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");

小提琴:http://jsfiddle.net/GTScL/

【讨论】:

    【解决方案2】:

    您可能想先修复您的自执行功能 然后在尝试将其传递给另一个函数之前为 html 创建一个变量

    (function ($) {
    
          $.fn.tasks = function () {
    
                var ele = $(this);
    
                $.ajax({
                        url: "include/tasks_handler.php?action=gettasks&list=default",
                        beforeSend: function() {
                               ele.html(ajax_load);
                        },
                        success: function(html){
                               ele.html(html);
                        }
                });
          };
    
    }( jQuery )); // Bracket goes after
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-08-19
      • 2010-11-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-05-13
      • 2019-11-06
      • 2017-11-28
      相关资源
      最近更新 更多