แสดง-ซ่อน แถวของตาราง

ตัวอย่างการ แสดง-ซ่อน แถวของตารางโดยการคลิกลิงค์ และ สร้างตารางตามที่กำหนดด้วย array โดย Javascript

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>Untitled Document</title>
<meta http-equiv="Content-Type" content="text/html; charset=TIS-620">
<meta http-equiv="Content-Style-Type" content="text/css">
<meta http-equiv="Content-Script-Type" content="text/javascript">
<script type="text/javascript">
//ข้อมูลในตารางที่ต้องการสร้าง
var data=[
  ['แดง','เขียว','น้ำเงิน'],
  ['เทา','ดำ','ขาว']
  ]
function addRows()
{
  var root = document.getElementById( 'my_table' ).getElementsByTagName( 'tbody' )[0];
  for ( var n = 0 ; n < data.length ; n++ )
  {
    var crow=document.createElement( 'tr' );
    crow.style.backgroundColor = '#E5E5E5'
    var ccel = document.createElement( 'td' );
    ccel.appendChild( document.createTextNode( 'แสดง' ) );
    ccel.setAttribute( 'colSpan' , data[0].length );
    ccel.style.cursor='pointer';
    ccel.onclick = function() { showhide( this ) }
    crow.appendChild( ccel );
    root.appendChild( crow );
    var row = document.createElement( 'tr' );
    row.style.display = 'none';
    for ( var j = 0 ; j < data[0].length ; j++ )
    {
      var cel = document.createElement( 'td' );
      cel.appendChild( document.createTextNode( data[n][j] ) )
      row.appendChild( cel )
    }
    root.appendChild( row )
  }
}

function showhide( c )
{
  var next = c.parentNode.nextSibling;
  while( next.nodeName.toLowerCase() != 'tr' )
  {
    next = next.nextSibling;
  }
  next.style.display = ( next.style.display == '' ) ? 'none' : '';
  c.firstChild.data = ( c.firstChild.data == 'แสดง' ) ? 'ซ่อน' : 'แสดง';
}

onload = addRows;
</script>
</head>
<body>
<table width="400" border="1" id="my_table">
<tbody>
<tr>
<td width="33%"><strong>คอลัมน์ 1</strong></td>
<td width="33%"><strong>คอลัมน์ 2</strong></td>
<td><strong>คอลัมน์ 3</strong></td>
</tr>
</tbody>
</table>
</body>
</html>
ผู้เขียน goragod โพสต์เมื่อ 31 มี.ค. 2551 เปิดดู 16,847 ป้ายกำกับ HTMLJavascript
^