<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Document</title> <style> *{ margin: 0; padding: 0; } .father{ width: 200px; height: 200px; background: red; } .son{ width: 100px; height: 100px; background: blue; } </style> <script src="./jquery-1.10.1.min.js"></script> </head> <body> <script> $(function() { //什么是事件委托? //就是我叫你做一个东西,你做好了给我。核心:我完全不用动手的哈. /*$("button").click(function()
{
$("ul").append("
cyg
");
});
$("ul>li").click(function()
{
console.log($(this).html());
});
*/ /*
在jQuery中,如果通过核心函数找到的元素不止一个, 那
么在添加事件的时候,jQuery会遍历所有找到的元素,给所有找到的元素添加事件
*/ /*
以下代码的含义, 让ul帮li监听click事件
之所以能够监听, 是因为入口函数执行的时候ul就已经存在了, 所以能够添加事件
之所以this是li,是因为我们点击的是li, 而li没有click事件, 所以事件冒泡传递给了ul,ul响应了事件, 既然事件是从li传递过来的,所以ul必然指定this是谁
*/ $("ul").delegate("li","click",function() { console.log($(this).html()); console.log(this); }) }); </script> <ul> <li>我是第1个li</li> <li>我是第2个li</li> <li>我是第3个li</li> </ul> <button>新增一个li</button> </body> </html>