The use and differences of bind and live in jQuery


Before we started with these two methods, we used the click() method

$("a").click(function() {
     alert("hello");
});

The click() method is a simple method for the bind() method. In the bind (), JQuery all JavaScript event objects like focus, mouseover, and resize, Can be passed in as a type parameter.

Parameter: the type, [data], function (eventObject) Such as:

$("p").bind("click",function(){
     alert("hello");
})

You can also pass arguments

var message = "how are you!";
$("p").bind("click",{msg:message},function(e){
     alert(e.data.msg);
})

**Live () appends an event handler to all matched elements, Even if the element is added later. As follows: **

<tr class="mytr">
     <td class="mytd">Click me</td>
</tr>
$(".mytd").bind("click",function(){
      alert("hello");
})

Clicking on Clike me will bring up hello

At this point, a new element is added

$(".mytr").after("<tr><td class='mytd'> After adding the </td></tr>");

In this case, using bind and clicking “after” will not be executed Use the live() method instead

$(".mytd").live("click",function(){
 alert("hello");
})

The.live() method works for an element that has not been added to the DOM because of the use of event delegates: An event handler bound to an ancestor element can respond to an event that fires on a descendant. The event handler passed to.live() is not bound to the element, but is bound to the root node of the DOM tree as a special event handler.