jQuery 事件 - delegate() live() 方法
转自:http://www.w3school.com.cn/jquery/event_delegate.asp
delegate() 方法为指定的元素(属于被选元素的子元素)添加一个或多个事件处理程序,并规定当这些事件发生时运行的函数,而 live()方法则为被选元素附加一个或多个事件处理程序,并规定当这些事件发生时运行的函数。
使用 delegate() live() 方法的事件处理程序适用于当前或未来的元素(比如由脚本创建的新元素),而利用$("selector").click(function) 方法的事件处理则不会对未来的元素(比如脚本创建的新元素)起作用。
实例:
delegate()方法:
<html>
<head>
<script type="text/javascript" src="/jquery/jquery.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("div").delegate("p","click",function(){
$(this).slideToggle();
});
$("button").click(function(){
$("<p>这是一个新段落。</p>").insertAfter("button");
});
});
</script>
</head>
<body>
<div style="background-color:yellow">
<p>这是一个段落。</p>
<p>请点击任意一个 p 元素,它会消失。包括本段落。</p>
<button>在本按钮后面插入一个新的 p 元素</button>
</div>
<p><b>注释:</b>通过使用 delegate() 方法,而不是 live(),只有 div 元素中的 p 元素会受到影响。</p>
</body>
</html>
live() 方法:
<html>
<head>
<script type="text/javascript" src="/jquery/jquery.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("p").live("click",function(){
$(this).slideToggle();
});
$("button").click(function(){
$("<p>This is a new paragraph.</p>").insertAfter("button");
});
});
</script>
</head>
<body>
<p>这是一个段落。</p>
<p>点击任意 p 元素会令其消失。包括本段落。</p>
<button>在本按钮后面插入新的 p 元素</button>
<p><b>注释:</b>通过使用 live() 方法而不是 bind() 方法,新的 p 元素同样会在点击时消失。</p>
</body>
</html>
$("selector").click(function )
<html>
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs
/jquery/1.4.0/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("p").click(function(){
$(this).slideToggle();
});
$("button").click(function(){
$("<p>这是一个新段落。</p>").insertAfter("button");
});
});
</script>
</head>
<body>
<div style="background-color:yellow">
<p>这是一个段落。</p>
<p>请点击任意一个 p 元素,它会消失。包括本段落。</p>
<button>在本按钮后面插入一个新的 p 元素</button>
</div>
<p><b>注释:</b>通过使用 delegate() 方法,而不是 live(),只有 div 元素中的 p 元素会受到影响。</p>
</body>
</html>
深度解析:
http://developer.51cto.com/art/201103/249694.htm