简体   繁体   中英

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. If I replace $(".the_lead") with $this, it won't perform it's action.

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):

[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. 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.

Additionally, caching it seems like you'd want to cache only one of the .the_lead elements, no? That's how your code reads. with $this = $(this); but then within the function you seem to want all elements with the class .the_lead . Try directly caching it like this instead. $this = $('.the_lead');

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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