<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>delegate_代表</title> <script type="text/javascript" src="js/jquery-1.12.4.min.js"></script> <script type="text/javascript"> $(function(){ // $('.list li').click(function(){ // $(this).css({'backgroundColor':'plum'},) // }) // // 常規寫法, 此方法,在執行的時候, 是把當前語句下的八個li依次進行綁定.之后添加新條件的時候就不會再進行綁定. // var $li = $('<li>9</li>'); // // 新建一個變量, 賦值給li變量. // $('.list').append($li); // // 把變量liappend到ul標簽里面,完成增加新元素的操作. // // 使用之前寫法的話, 一方面需要綁定與元素數量相等的次數, 性能不好. 且, 之后新添加的元素不能使用該式樣. $('.list').delegate('li','click',function(){ $(this).css({'backgroundColor':'red',}) }) var $li = $('<li>9</li>'); $('.list').append($li); // 這里新增元素也可以使用該式樣. // 一方面是性能提升, 一方面是添加新子元素也可以享受式樣, 減少代碼量. // 所以, 式樣操作的時候, 多使用 事件代理(委托) }) </script> <style type="text/css"> .list{ width: 100%; background: tan; list-style: none; padding: 5px; } .list li{ height: 30px; background: lime; margin: 10px; } </style> </head> <body> <ul class="list"> <li>1</li> <li>2</li> <li>3</li> <li>4</li> <li>5</li> <li>6</li> <li>7</li> <li>8</li> </ul> </body> </html>
