Bind cannot be used for future element binding events,
1. You can use live instead, but pay attention to the jquery version. According to the official documentation, live and delegate are not recommended from 1.7, and live is removed from 1.9.
2. We recommend that you use on instead (Note: Only supported in version 1.7 and later ). Usage: on (events, [selector], [data], fn)
Copy codeThe Code is as follows:
// Put it in $ (function () {}).
$ (Document). on ("click", "# testDiv", function (){
// $ (This) here refers to $ ("# testDiv"), rather than $ (document)
});
3. When you only want to bind a one-time event processing function to a specific event (such as click) that matches each element, use. one () can replace on. Note that not all [selector] can be executed once, but all of these [select] can be executed once, it is also effective for future elements.
4. If a div contains three buttons for addition, deletion, and modification, You need to bind events, as shown in the following code:
Copy codeThe Code is as follows:
$ ('# Btn-add'). click (function (){});
$ ('# Btn-del'). click (function (){});
$ ('# Btn-edit'). click (function (){});
The downside of writing this is that there is no reason to see the structural connection between the three, and there is no reason for the event to bubble up.
Let's take a look at CoffeeDeveloper's suggestions on jQuery event binding. You can write them as follows:
Copy codeThe 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 },
}
});
Is writing like this much better? (. coffee () is a custom function. Can you write this function by yourself ?), However, if the bound function is long, the Code still looks messy.
Copy codeThe Code is as follows:
$ ('# BtnContainer ')
. On ('click', '# btn-add', function (){})
. On ('click', '# btn-del', function (){})
. On ('click', '# btn-edit', function (){});
This writing method also avoids the two disadvantages mentioned above and does not seem messy.