What's the difference between `on` and `live` or `bind`?

前端 未结 7 1982
迷失自我
迷失自我 2020-11-22 16:00

In jQuery v1.7 a new method, on was added. From the documentation:

‘The .on() method attaches event handlers to the currently se

7条回答
  •  太阳男子
    2020-11-22 16:43

    (My opening sentence made more sense before you changed the question. Originally you'd said "What's the difference with live?")

    on is more like delegate than it is like live, it's basically a unified form of bind and delegate (in fact, the team said its purpose is "...to unify all the ways of attaching events to a document...").

    live is basically on (or delegate) attached to the document as a whole. It's deprecated as of v1.7 in favor of using on or delegate. Going forward, I suspect we'll see code using on solely, rather than using bind or delegate (or live)...

    So in practice, you can:

    1. Use on like bind:

      /* Old: */ $(".foo").bind("click", handler);
      /* New: */ $(".foo").on("click", handler);
      
    2. Use on like delegate (event delegation rooted in a given element):

      /* Old: */ $("#container").delegate(".foo", "click", handler);
      /* New: */ $("#container").on("click", ".foo", handler);
      
    3. Use on like live (event delegation rooted in the document):

      /* Old: */ $(".foo").live("click", handler);
      /* New: */ $(document).on("click", ".foo", handler);
      

提交回复
热议问题