jquery的一些链式绑定事件

对同一个dom节点可以绑定多个事件,采用jquery的链式操作是种不错的选择,当然,以下代码只能适用于已存在dom树里的节点;

 1 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
 2 <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
 3 <head>
 4     <meta http-equiv="Content-Type" content="text/html;charset=UTF-8">
 5     <title>jquery的链式绑定</title>
 6 </head>
 7 <body>
 8     <input type="text" id="test" />
 9     <script src="jquery-1.9.1.js"></script>
10     <script>
11         $(function(){
12             $("#test").bind("focus", function(e){
13                 console.log("focus");
14             }).bind("blur", function(e){
15                 console.log("blur");
16             }).bind("click", function(e){
17                 console.log("click");
18             }).bind("propertychange input", function(e){
19                 console.log("inout");
20             });
21         });
22     </script>
23 </body>
24 </html>

 对于动态添加的节点,可以用jquery的on来绑定

 1 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
 2 <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
 3 <head>
 4     <meta http-equiv="Content-Type" content="text/html;charset=UTF-8">
 5     <title>jquery的链式绑定</title>
 6 </head>
 7 <body>
 8     <button id="btn">点我</button>
 9     <script src="jquery-1.9.1.js"></script>
10     <script>
11         $(function(){
12             $("#btn").bind("click", function(e){
13                 var input = "<input type='text' id='test' />";
14                 $("body").append(input);
15             });
16 
17             $(document).on("focus", "#test", function(e){
18                 console.log("focus");
19             }).on("blur", "#test", function(e){
20                 console.log("blur");
21             }).on("click", "#test", function(e){
22                 console.log("click");
23             }).on("propertychange input", "#test", function(e){
24                 console.log("input");
25             });
26         });
27     </script>
28 </body>
29 </html>
原文地址:https://www.cnblogs.com/aissd/p/5085456.html