JQuery USES bind live or on to bind events for future elements

  • 2020-03-30 02:40:59
  • OfStack

Bind cannot be used for binding events for future elements,

1. You can use live instead, but notice the jquery version. According to the official documentation, live and delegate have not been recommended since 1.7, and live has been removed from 1.9.

2. It is recommended to use on instead (note: version 1.7 or above is only supported). Usage: on (events, [the selector], [data], fn)
 
//$(function(){})
$(document).on("click", "#testDiv", function(){ 
//Here $(this) refers to $("#testDiv"), not to $(document)
}); 

3. When you only want to bind a one-time event handler to a specific event for each matched element (like click), use.one() instead of on. Note that instead of executing once on all [selectors], you execute once in all on these [selectors], and this will work for future elements.

4. If there are three buttons in a div that need to bind events, such as the following:
 
$('#btn-add').click(function(){}); 
$('#btn-del').click(function(){}); 
$('#btn-edit').click(function(){}); 

The disadvantage of writing this way is that there is no structural connection between the three, and no reason for the event to bubble.

Take a look at CoffeeDeveloper's recommended way of thinking about jQuery's event bindings, which 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 }, 
} 
}); 

(.coffee() is a custom function. Can you write it yourself? , except that if the bound function is long, the code still looks 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.

Related articles: