jQuery綁定事件
阿新 • • 發佈:2017-09-03
其它 col bin round end 執行 class 作用 div
1.事件綁定的方式
事件 DOM:三種綁定方式 jQuery: #前面幾種調用的全是on $(‘.c1‘).click() $(‘.c1‘).bind(‘click‘,function(){}) $(‘.c1‘).unbind(‘click‘,function(){}) $(‘.c1‘).delegate(‘a‘,‘click‘,function(){}) #不同於其它,有委托的作用 $(‘.c1‘).undelegate(‘a‘,‘click‘,function(){}) $(‘.c1‘).on(‘click‘,function(){}) $(‘.c1‘).off(‘click‘,function(){})
2. 由於程序是從上往下執行,所以對新輸入的沒有綁定alert事件。
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <input id="t1" type="text"/> <input id="a1" type="button" value="添加"/> <ul id="ul"> <li>123</li> <li>456</li> </ul> <script src="jquery-1.12.4.js"></script> <script> $(‘#a1‘).click(function(){ var v=$(‘#t1‘).val(); var temp="<li>"+v+"</li>"; $(‘#ul‘).append(temp); }); $(‘ul li‘).click(function(){ v=$(this).text(); alert(v); }) </script> </body> </html>
所以需要重新綁定
3. delegate具有委托的作用,不同於其它幾個。
click不行,bind不行,on不行,delegate可以。委托。
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <input id="t1" type="text"/> <input id="a1" type="button" value="添加"/> <ul id="ul"> <li>123</li> <li>456</li> </ul> <script src="jquery-1.12.4.js"></script> <script> $(‘#a1‘).click(function(){ var v=$(‘#t1‘).val(); var temp="<li>"+v+"</li>"; $(‘#ul‘).append(temp); }); $(‘ul‘).delegate(‘li‘,‘click‘,function(){ v=$(this).text(); alert(v); }) </script> </body> </html>
jQuery綁定事件