ใน jQuery เวอร์ชั่น 1.4 มี event ที่ชื่อ live และ die ที่ทำให้เราสามารถกำหนด หรือยกเลิก event ต่างๆ ให้กับ elements ที่ถูกดึงมาแสดงด้วย ajax หรือที่เรียกว่าข้อมูลจาก xhr ได้
ดูตัวอย่างประกอบ
div id=i_content
div id=i_debug
เมื่อเราคลิกที่ div id=i_content สีเหลืองอ่อน
ก็จะมีการนำ span id=i_span สีฟ้า และข้อความว่า message มาแสดงใน div สีเหลืองอ่อน
ด้วยคำสั่ง
$("#i_content").click(function(){
var xhrData = "<span id='i_span'>message</span>"
$("#i_content").html(xhrData);
});
ถ้าเราต้องการเรียก span id=i_span สีฟ้า นั้นมาใช้งานอีกที เช่น ต้องการนำข้อความใน span id=i_span สีฟ้า มาแสดงใน div id=i_debug สีแดงอ่อน
ด้วยคำสั่งข้างล่าง ต่อไปนี้ ไม่สามารถทำได้
$("span#i_span").click(function(){
$("#i_debug").html($("span#i_span").html());
});
แต่ด้วยคุณสมบัติของ event live ของ jQuery 1.4 สามารถทำได้
ด้วยคำสั่งต่อไปนี้
$("span#i_span").live('click',function(){
$("#i_debug").html($("span#i_span").html());
});
และสามารถยกเลิกความสามารถนี้ด้วย die event
ด้วยคำสั่งต่อไปนี้
$("span#i_span").die('click');
โค้ดตัวอย่าง
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>jquery get object from ajax</title>
<style type="text/css">
#i_content{
background-color:#FFC;
width:200px;
height:35px;
display:block;
}
#i_debug{
background-color:#FCC;
width:200px;
height:35px;
display:block;
}
#i_span{
background-color:#6CF;
}
</style>
</head>
<body>
<script type="text/javascript" src="js/jquery-1.4.1.min.js"></script>
<script type="text/javascript">
$(function(){
$("#i_content").click(function(){
var xhrData = "<span id='i_span'>message</span>"
$("#i_content").html(xhrData);
});
$("span#i_span").click(function(){
$("#i_debug").html("I click the span id i_span");
});
$("#cancel_live").click(function(){
$("span#i_span").die('click');
$("#i_debug").html("");
});
$("#use_live").click(function(){
$("span#i_span").live('click',function(){
$("#i_debug").html($("span#i_span").html());
});
});
});
</script>
div id=i_content
<br />
<div id="i_content"></div>
<br />
div id=i_debug
<br />
<div id="i_debug"></div>
<br />
<button id="use_live">Use live() event</button>
<button id="cancel_live">Use die() event</button>
</body>
</html>
อ่านเพิ่มเติม
https://api.jquery.com/