Home > Web Front-end > JS Tutorial > body text

In jQuery, use bind, live or on_jquery to bind future element events.

WBOY
Release: 2016-05-16 16:51:58
Original
1069 people have browsed it

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)

Copy code The code is as follows:

//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:
Copy code The code is as follows:

$('#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:
Copy code The code is as follows:

$("#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,
Copy code The code is as follows:
$('#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.
Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!