You cannot use bind for future element binding events.
1. You can use live instead, but pay attention to the version of jquery. According to the official documentation, live and delegate are not recommended starting from 1.7 and will be removed in 1.9 live.
2. It is recommended to use on instead (note: only supported by versions 1.7 and above). Usage: on(events,[selector],[data],fn)
//It is only valid when placed in $(function(){})
$(document).on("click", "#testDiv", function(){
//Here $(this) refers to $( "#testDiv"), not $(document)
});
3. When you only want to generate a specific event for each matching element (like click ) When binding a one-time event processing function, just use .one() instead of on. Note that it is not executed once on all [selectors], but only once on these [selects]. , also valid for future elements.
4. If there are three buttons of add, delete or modify in a div that need to be bound to events, write like the following:
$('#btn-add').click(function(){});
$('#btn-del').click (function(){});
$('#btn-edit').click(function(){});
The disadvantage of writing like this: you can’t see the difference between the three Structural connections, no reason for events to bubble up.
Let’s take a look at CoffeeDeveloper’s recommendations for some thoughts on jQuery event binding. It can be written like this:
$("#btnContainer").coffee({
click: {
"#btn-add": function(){ //do something },
"#btn-del": function(){ //do something },
"#btn-edit": function(){ //do something }
} ,
mouseenter:{
"#btn-abc": function(){ //do something },
}
});
Writing it like this, doesn’t it look much better? (.coffee() is a custom function, can you write this function yourself?), but if the bound function is relatively long, the code still feels a bit messy,
$('#btnContainer')
.on('click','# btn-add', function(){})
.on('click','#btn-del', function(){})
.on('click','#btn-edit' ,function(){});
This way of writing also avoids the two disadvantages mentioned above and looks less messy.