【问题标题】:Access $this in jquery plugin event在 jquery 插件事件中访问 $this
【发布时间】:2011-08-31 19:56:44
【问题描述】:

我正在编写一个 jQuery 插件,它涉及将事件绑定到 window.scroll。 在 window.scroll 中执行的操作取决于调用原始初始化时传入的设置。

如何在绑定事件中访问数据元素或 this?

 (function($) {
    var methods = {
        init : function(options) {
            return this.each(function() {
                $(window).bind("scroll.myPlugin", methods.windowOnScroll);
            });
        },
        windowOnScroll : function() {
            var $this = $(this);
            var data = $this.data("scrollingLoader");
            if (data.something) {
                 // ...
            }
        }
  })(jQuery);

【问题讨论】:

    标签: jquery jquery-plugins


    【解决方案1】:

    jQuery 提供了一个方便的函数$.proxy,它可以进行跨浏览器的函数绑定。

    (function($) {
        var methods = {
            init : function(options) {
                return this.each(function() {
                    $(window).bind("scroll.myPlugin", $.proxy(methods.windowOnScroll,methods));
                });
            },
            windowOnScroll : function() {
                var $this = $(this);
                var data = $this.data("scrollingLoader");
                if (data.something) {
                     // ...
                }
            }
      })(jQuery);
    

    $.proxy 函数返回一个函数,该函数将始终在第二个参数的上下文中执行第一个参数中传递的函数。 http://api.jquery.com/jQuery.proxy

    【讨论】:

      【解决方案2】:

      你需要定义你的范围:

      (function($) {
          var methods = {
              init : function(options) {
                  return this.each(function() {
                      var scope = this;
                      $(window).bind("scroll.myPlugin", function(){
                          methods.windowOnScroll.call(scope);
                      });
                  });
              },
              windowOnScroll : function() {
                  var $this = $(this);
                  var data = $this.data("scrollingLoader");
                  if (data.something) {
                       // ...
                  }
              }
        })(jQuery);
      

      【讨论】:

        猜你喜欢
        • 2023-04-10
        • 2020-11-25
        • 2023-04-04
        • 2022-12-09
        • 1970-01-01
        • 2014-07-17
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多