jQuery插件选择器访问范围

时间:2013-02-08 16:05:58

标签: javascript jquery jquery-plugins

我试图在下面的闭包内部访问jQuery对象的选择器,这样我就不必指定它和/或缓存它。如果我用$ this替换$(" .the_lead"),它将无法执行该操作。

调用插件

$(".the_lead").scroll_lead({speedup: 400});

阻止

var $this = $(this);

$(window).scroll(function() {

    var window_height = $(window).height();
    var document_height = $(document).height();
    var hide_lead;
    var scrollTop = $(window).scrollTop();

    console.log($this);

    if(!hide_lead){

        if(scrollTop>(document_height/2)){
            $(".the_lead").slideDown(options.speedup);
            }else{
            $(".the_lead").slideUp(500,function(){
                $(".the_lead").hide();
          });}
         }


        $('#hide_lead').click(function(e){
            //$(".the_lead").parent().parents('div').hide();
            hide_lead = true;           
            e.preventDefault();
        });     

    }); 

$(this)的控制台输出:

[selector: ".the_lead", context: document, constructor: function, init: function, selector: ""…]
context: #document
length: 0
selector: ".the_lead"
__proto__: Object[0]

1 个答案:

答案 0 :(得分:1)

注意控制台输出的length: 0。窗口滚动事件或多或少地触发用户移动的每个像素。没有看到你的插件的更多代码,我无法确定,但我敢打赌$只有滚动事件第一次触发时这才是正确的。

此外,缓存它似乎你只想缓存一个.the_lead元素,不是吗?这就是你的代码的读取方式。使用$this = $(this);然后在函数中,您似乎想要所有具有类.the_lead的元素。请尝试直接缓存它。 $ this = $('。the_lead');