JS-表格数据的添加与删除、搜索

<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>JS练习-表格数据的添加与删除、搜索</title>
<style>

</style>
<script>
window.onload=function()
{
 var oTab=document.getElementById('table1')
 var oName=document.getElementById('name')
 var oAge=document.getElementById('age')
 var oBtn=document.getElementById('btn')
 var oSearch=document.getElementById('search')
 var oSearchBtn=document.getElementById('searchBtn')
 var id=oTab.tBodies[0].rows.length+1//定义序号变量

 
 oBtn.onclick=function()
 {
  var oTr=document.createElement('tr')
  
  var oTd=document.createElement('td')
  oTd.innerHTML=id++
  oTr.appendChild(oTd)
  
  var oTd=document.createElement('td')
  oTd.innerHTML=oName.value
  oTr.appendChild(oTd)
  
  var oTd=document.createElement('td')
  oTd.innerHTML=oAge.value
  oTr.appendChild(oTd)
  
  var oTd=document.createElement('td')
  oTd.innerHTML='<a href="javascript:;">删除</a>'
  oTr.appendChild(oTd)//添加表格行
  
  oTd.getElementsByTagName('a')[0].onclick=function()
  {
   oTab.tBodies[0].removeChild(this.parentNode.parentNode)
  
  }//删除表格行
    
  oTab.tBodies[0].appendChild(oTr)
  }
    
  oSearchBtn.onclick=function()
  {

   for( var i=0; i<oTab.tBodies[0].rows.length; i++)
   {
    var sTab=oTab.tBodies[0].rows[i].cells[1].innerHTML.toLowerCase()
             var sTxt=oSearch.value.toLowerCase()
    var attr=sTxt.split('')
    oTab.tBodies[0].rows[i].style.background=''
    for( var j=0; j<attr.length; j++)
    {
    if(sTab.search(attr[j])!=-1)
    {
     oTab.tBodies[0].rows[i].style.background='yellow'
    }

    }
   }
  }//模糊搜索,多关键字搜索
}

</script>
</head>

<body>
姓名:<input type="text" id="name"  placeholder="请输入姓名">
年龄:<input type="text" id="age"   placeholder="请输入年龄">
<input id="btn" type="button" value="添加"><br><br>
<input type="text" id="search" placeholder="请输入你的姓名">
<input type="button" id="searchBtn" value="搜索"><br><br>

<table id="table1" border="1" width="800px">
 <thead>
     <td>ID</td>
        <td>姓名</td>
        <td>年龄</td>
        <td>操作</td>
     </thead>
     <tbody>
      <tr>
            <td>1</td>
            <td>陈子君</td>
            <td>25</td>
            <td></td>
           
        </tr>
      <tr>
            <td>2</td>
            <td>Blue</td>
            <td>13</td>
            <td></td>
        </tr>
      <tr>
            <td>3</td>
            <td>张三</td>
            <td>45</td>
            <td></td>
        </tr>
      <tr>
            <td>4</td>
            <td>李四</td>
            <td>50</td>
            <td></td>
        </tr>
      <tr>
            <td>5</td>
            <td>S物流</td>
            <td>35</td>
            <td></td>
        </tr>  
      <tr>
            <td>6</td>
            <td>我</td>
            <td>27</td>
            <td></td>
        </tr>  
      <tr>
            <td>7</td>
            <td>surPrise</td>
            <td>30</td>
            <td></td>
        </tr>
   </tbody>
</table>
</body>
</html>

posted @ 2016-01-06 15:32  盗梦者  阅读(592)  评论(0编辑  收藏  举报