The difference between click of bind of live of delegate of in Query

  • 2020-03-29 23:52:07
  • OfStack

Click (), bind(), and live() are all methods used to execute the event. They have some differences before, and we should choose them as needed when using these methods.

1. The click() method is the click event method that we often use:


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

When you click < A> , output hello.

The 2. Click () method is an easy way to use the bind() method. In bind(), all jQuery JavaScript event objects, such as focus, mouseover, and resize, are passed in as type parameters. Let's look directly at an example in the jQuery documentation:


var message = "left";
$("a").bind("click", function() {
   alert(message);
   return false;
});var message = "right";
$("a").bind("contextmenu", function() {
   alert(message);
   return false;
});

In the above code, whether left click or right click < A> The output is always "right". To solve this problem, we can pass message as a data parameter to the bind() method, as follows:

var message = "left";
$("a").bind("click", { msg: message }, function(e) {
   alert(e.data.msg);
   return false;
});var
 message = "right";
$("a").bind("contextmenu", { msg: message }, function(e) {
   alert(e.data.msg);
   return false;
});

So when we left click < A> , output "left"; When right-click < A> , output "right".

As you can see, we generally use the click() method, but we use the bind() method when we need to handle the above case.

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


$("div.live").bind("click", function() {
   alert("success");
});

At this point, when you click the div with class live, output "success". At this point, if a new element is added, it is as follows:

$("<div class="live" href="#">live</div>").appendTo("body");

At this point, when the class is live tag is clicked using the above method, it is not executed. The reason is that the element was added after the bind() call, and the live() method allows the element added later to execute the event as well, as follows:

$("div.live").live("click", function() {
   alert("success");
});

This way, when we click on the a tag with class as live, we can also print "success" as usual if the a tag is added later. As for the reason, do not make specific explanation here, this article mainly compares the difference of several methods.


Related articles: