简体   繁体   English

jQuery插件选择器访问范围

[英]jQuery Plugin selector access scope

I'm trying to access the selector of the jQuery object inside of the closure below so that I don't have to specify it and/or cache it. 我正在尝试在下面的闭包内部访问jQuery对象的选择器,以便不必指定它和/或对其进行缓存。 If I replace $(".the_lead") with $this, it won't perform it's action. 如果我将$(“。the_lead”)替换为$ this,它将无法执行操作。

Invoking the plugin 调用插件

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

Block

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();
        });     

    }); 

Console Output for $(this): $(this)的控制台输出:

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

Notice the length: 0 output by the console. 请注意length: 0控制台输出为length: 0 The window scroll event fires more or less every pixel the user moves. 窗口滚动事件或多或少会触发用户移动的每个像素。 Without seeing more of your plugin's code I couldn't be sure, but I'd bet $this is correct only the first time the scroll event fires. 我不确定自己没有看到更多插件的代码,但我敢打赌,只有在scroll事件首次触发时,$ this才是正确的。

Additionally, caching it seems like you'd want to cache only one of the .the_lead elements, no? 此外,缓存似乎只希望缓存.the_lead元素之一,不是吗? That's how your code reads. 这就是您的代码读取的方式。 with $this = $(this); 其中$this = $(this); but then within the function you seem to want all elements with the class .the_lead . 但是在函数中,您似乎想要所有带有.the_lead类的.the_lead Try directly caching it like this instead. 尝试像这样直接缓存它。 $this = $('.the_lead'); $ this = $('。the_lead');

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM