最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Multiple scroll event definition, and discriminatory event unbinding - Stack Overflow

programmeradmin5浏览0评论

I ask a specific question about jquery scroll events, but it seems like the answer could have implications to jquery events in general (which I am also interested in knowing).

Suppose that jquery plugin A (e.g., jquery.scrollspy.js) binds a scroll event to $(window)

Now say that some site imports plugin A, but it also has its own custom javascript file B, which binds another .scroll() event to $(window).

Later on, javascript file B wants to unbind its own scroll event, and leave jquery plugin A intact. How is this done?

and...

Is this method universal to all jquery events?

I ask a specific question about jquery scroll events, but it seems like the answer could have implications to jquery events in general (which I am also interested in knowing).

Suppose that jquery plugin A (e.g., jquery.scrollspy.js) binds a scroll event to $(window)

Now say that some site imports plugin A, but it also has its own custom javascript file B, which binds another .scroll() event to $(window).

Later on, javascript file B wants to unbind its own scroll event, and leave jquery plugin A intact. How is this done?

and...

Is this method universal to all jquery events?

Share Improve this question edited Apr 21, 2013 at 20:22 Alex W 38.2k13 gold badges111 silver badges114 bronze badges asked Apr 21, 2013 at 20:12 Colin BroganColin Brogan 7481 gold badge10 silver badges27 bronze badges 1
  • For those interested in doing this without jQuery: stackoverflow./questions/4402287/… – Alex W Commented Apr 21, 2013 at 20:22
Add a ment  | 

3 Answers 3

Reset to default 8

jQuery remends to use on and off instead of bind and unbind.

function scrollEvent()
{
}
$(window).on('scroll',scrollEvent);
$(window).off('scroll',scrollEvent);

http://api.jquery./on/

Best to use jQuery's .on() and .off() methods rather than .bind() and .unbind().

As of jQuery 1.7, the .on() method is the preferred method for attaching event handlers to a document.

You can also namespace the event by adding a custom suffix to the event name. You can then access that particular event later (to unbind for example)...

$(window).on('scroll.myscroll', function () { 
    // do something on scroll event
});

an den...

$(window).off('scroll.myscroll'); // unbind my namespaced scroll event

See https://css-tricks./namespaced-events-jquery/

This is easy. Didn't do enough research before asking question:

var fileBScrollEvent = function() {
    // do something on scroll event
}


$(window).bind('scroll',fileBScrollEvent);

...later on in the code...

$(window).unbind('scroll',fileBScrollEvent);
发布评论

评论列表(0)

  1. 暂无评论