
ขอเล่นกับตารางและ jQuery อีกสักบทความ เหมือนเดิมครับ เน้นที่ง่ายๆ เอาไปประยุกต์ต่อ บทความในตอนนี้สิ่งที่จะทำคือ เมื่อท่านคลิกแถวไหนของตาราง แถวนั้นก็จะถูกลบออกไปจากตารางทันที มาดูกันครับว่า ทำอย่างไร
โครงสร้าง HTML :
<table id="table"> <tr> <th>ลำดับ</th> <th>สาขา</th> </tr> <tr> <td>1</td> <td>สุรวงศ์</td> </tr> <tr> <td>2</td> <td>เพชรบุรีตัดใหม่</td> </tr> </table> |
include jQuery เข้ามา :
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script> |
เขียนโค้ด :
$(document).ready(function(){ $('#table td').click(function(){ $(this).parent().hide(); }); }) |
.parent ก็คือแม่ของ td ก็คือ tr
.hide ซ่อนมันซะ (หายไปจากหน้าจอก็เหมือนลบนั่นแหละ)
โค้ดทั้งหมด :
<!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" />
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
<title>Delete row from table</title>
<script type="text/javascript">
$(document).ready(function(){
$('#table td').click(function(){
$(this).parent().hide();
});
})
</script>
</head>
<body>
<table id="table">
<tr>
<th>ลำดับ</th>
<th>สาขา</th>
</tr>
<tr>
<td>1</td>
<td>สุรวงศ์</td>
</tr>
<tr>
<td>2</td>
<td>เพชรบุรีตัดใหม่</td>
</tr>
</table>
</body>
</html> |
แสนจะง่ายดาย เหมือนเดิม





Leave a Reply