jQuery插件打破了this.each

我正在编写一个插件并尝试将函数包装在每个方法中,但它会破坏插件。 如果块内容未包含在“this.each”插件中,则可以使用。 我明白为了传递多个选择器,我需要“返回this.each”或不? 我也想消除在插件中使用选择器的需要,例如“#the_lead”,而不是使用“this”。

(function($) { $.fn.scroll_lead = function (options) { var defaults = { speedup: 500 }; var options = $.extend({}, defaults, options); return this.each(function () { var $window_height = $(window).height(); var $document_height = $(document).height(); var $hide_lead; $(window).scroll(function () { var $scrollTop = $(window).scrollTop(); if (!$hide_lead) { if ($scrollTop > ($document_height / 2)) { $("#the_lead").slideDown(options.speedup); } else { $("#the_lead").slideUp(500, function () { $(this).hide(); }); } } }); $('#hide_lead').click(function (e) { $(this).parent().parents('div').hide(); hide_lead = true; e.preventDefault(); }); }); }; })(jQuery); 

一些事情;

  1. 将$(this)分配给$ this并在插件内的任何函数内使用它,在教程http://docs.jquery.com/Plugins/Authoring中说 。

     return this.each(function () { var window_height = $(window).height(); var document_height = $(document).height(); var hide_lead; $this = $(this); $(window).scroll(function () { var scrollTop = $(window).scrollTop(); if (!hide_lead) { if (scrollTop > (document_height / 2)) { $this.slideDown(options.speedup); } else { $this.slideUp(500, function () { //$(this).hide(); }); } } }); $this.click(function (e) { $(this).parent().parents('div').hide(); hide_lead = true; e.preventDefault(); }); }); 
  2. 尽量避免操纵插件中的父对象,包括$(window)和$(document)。

    可以读取窗口和文档的属性,但如果在插件中操作它,它将按选择器的次数进行操作。

    在你的代码中,因为你使用this.each,你会多次绑定窗口的滚动function。 例如,$(“div”)。scroll_lead()将’scroll’方法绑定到窗口,与文档的标签一样多。 这同样适用于$(document)和插件目标的所有父元素。

  3. 如果可能并且是您的意图,请使用元素滚动方法,而不是窗口滚动。

    获取滚动值$(el).scrollTop()

    要向下滚动,$(el).scrollTop(NUMBER)

    要绑定onScroll方法,$(el).scroll(functtion(){…})

希望能帮助到你

首先,您的语法不正确。

each都不会存在this因为这是函数的上下文,而不是jquery所知道的元素。

尝试$(this).each会让你更接近。

记住Jquery.Each不能对不是对象或数组的东西进行迭代,所以要确保你想要实现的东西是有意义的。

你想在这里实现什么目标?