2010-11-29 14 views
27

どのようにして削除して$(window).scrollを追加することができますか?私は、変数を格納し、いくつかのイベントの後、それを再利用する必要があります$(ウィンドウ)を追加し、削除します。jQueryのは.scroll(関数()?

// here i store my var 
$(window).scroll(function(){ 
    myScroll = $(window).scrollTop() 
}); 

$("#itemUnbind").click(function(){ 
    // here i need to remove the listener   
}); 

$("#itemBind").click(function(){ 
    // here i need to add listener again  
}); 

ありがとう。あなたは、変数内の関数を格納し、それを削除するoffを使用する必要が

答えて

63

var scrollHandler = function(){ 
    myScroll = $(window).scrollTop(); 
} 

$("#itemBind").click(function(){ 
    $(window).scroll(scrollHandler); 
}).click(); // .click() will execute this handler immediately 

$("#itemUnbind").click(function(){ 
    $(window).off("scroll", scrollHandler); 
}); 
+0

は、それが私 – Dee

+1

@Deeの罰金です...ありがとうございました - これはあなたのために働く場合は、それをマークしてくださいとして"ティック"アイコンをクリックして答えを返します。 – Fenton

+3

これは、次のようにする必要があります: $( "#itemUnbind"){ $(ウィンドウ).unbind( "scroll"、scrollHandler); }); –