[英]jQuery Plugin selector access scope
我正在嘗試在下面的閉包內部訪問jQuery對象的選擇器,以便不必指定它和/或對其進行緩存。 如果我將$(“。the_lead”)替換為$ this,它將無法執行操作。
調用插件
$(".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]
請注意length: 0
控制台輸出為length: 0
。 窗口滾動事件或多或少會觸發用戶移動的每個像素。 我不確定自己沒有看到更多插件的代碼,但我敢打賭,只有在scroll事件首次觸發時,$ this才是正確的。
此外,緩存似乎只希望緩存.the_lead元素之一,不是嗎? 這就是您的代碼讀取的方式。 其中$this = $(this);
但是在函數中,您似乎想要所有帶有.the_lead
類的.the_lead
。 嘗試像這樣直接緩存它。 $ this = $('。the_lead');
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.