Sometimes we add the DOM structure dynamically on the page, and when we want to add events to these nodes we need to bind a series of operations on this node.
<ahref="#"onclick= "addbtn ()">Addbtn</a> <DivID= "MDiv"> <Buttonclass= "Cbtn"onclick= "alert (11111)">Button1</Button> <Buttonclass= "Cbtn">Button2</Button> <Buttonclass= "Cbtn">Button3</Button> </Div>
<script type= "Text/javascript" > 2functionaddbtn () {3 $ (' #mDiv '). Append (' <button class= ' cbtn ' >button5</button> ') 4 } 5 JQuery (function($){ 6//use on instead of live and delegate (live for performance reasons have been discarded, replaced by delegate), the New button added to MDiv will still have bound events7 $ (' #mDiv '). On (' click ', '. cbtn '),function(index, eledom) {8 Alert ($ ( This). HTML ())9 });10//use on instead of bind$ ('. Cbtn '). On (' click ',function(){Alert ($ ( This). HTML ())13 })14//Note:15/*16 1, whether using bind, on, delegate, click (function ()) is a duplicate binding, that is, the binding of the same type of event is placed in an event queue, executed sequentially, after the bound event will not replace the previously bound, for on using off, Delegate with Undelegate,bind and click to unbind, for example unbind (type) is passed as the event type, and all event bindings are solved if the type is not passed It should be noted that the element itself is not unbind (such as Button1) 17 2, to bind custom events, such as ' open ', the above functions can be used, but the activation needs to use TRIGGER18 19 Summary: 20 We recommend using the on function, the binding form is $ ('. MyClass '). On ({click:function (eledom) {... do someting ... },24 dbclick:function (eledom) {... do someting ... 26}27 .... )*/30 }</script>
Bind (TYPE,[DATA],FN) binds event handlers for specific events of each matching element
$ ("a"). Bind ("click", Function () {alert ("OK");});
Live (TYPE,[DATA],FN) attaches an event handler function to all matching elements, even if the element is added later in the
$ ("a"). Live ("Click", Function () {alert ("OK");});
Delegate (SELECTOR,[TYPE],[DATA],FN) The specified element (which belongs to the child element of the selected element) adds one or more event handlers and specifies the function to run when these events occur
$ ("#container"). Delegate ("A", "click", Function () {alert ("OK");})
On (EVENTS,[SELECTOR],[DATA],FN) an event handler that is bound to one or more events on the selection element
Difference:
. Bind () is directly bound on the element
. Live () is bound to an element by bubbling way. More appropriate for the list type, bound to the document DOM node. and. Bind () have the advantage of supporting dynamic data.
. Delegate () is a more precise, small-scale use of event proxies with better performance. Live ()
. On () is the latest 1.9 version of the new event binding mechanism that incorporates the previous three ways
Original address: http://www.cnblogs.com/gaojun/p/3497582.html
JQ Event Bindings