click(), bind(), and live() are all methods used when executing events. They have some differences before. We should choose according to our needs when using these methods.
is clicked, hello is output.
2. The click() method is a simple method of the bind() method. In bind(), all jQuery JavaScript event objects, such as focus, mouseover, and resize, can be passed in as the type parameter. 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 you click left or right on , it outputs "right".
It can be seen that under normal circumstances we can just use the click() method. When we need to deal with the above situation, we have to use the bind() method.
3.live() attaches an event handler to all matching elements, even if the element is added later. is as follows:
$("div .live").bind("click", function() {
alert("success");
});
At this time, when the div with class live is clicked When, "success" is output. At this time, if a new element is added, it is as follows:
$("
live
").appendTo("body");
At this time, when using the above When the method clicks on the a tag with class live, it will not be executed. The reason is that this element is added after calling bind(), and using the live() method allows elements added later to also execute corresponding events, as follows:
$("div.live").live("click", function() {
alert("success ");
});
In this way, when we click the a tag with class live, if the a tag is added later, "success" can be output as usual. As for the reasons, I will not give a detailed explanation here. This article mainly compares the differences between several methods.
Finally, take a look at the delegate() method. I have not used this method myself so far. It should be available in 1.4.2.
One disadvantage of the live() method is that it does not support chain writing:
$("#test").children("a").live("mouseover", function() {
alert("hello");
});
The above writing method will not output. We can use delegate() to write it as:
$("#test").delegate("a", "mouseover", function() {
alert("hello");
});
In this way, the results we want can be output normally. This article summarizes the click(), bind(), live() and delegate() methods. It does not give a very detailed explanation. I only hope it can be helpful to everyone in their specific use.