功能实现:在table中点击某一行,选中前面的checkbox并改变背景色

html  table:

<table id="mytable">
   <tr>
    <th rowspan="2"><input type="checkbox" id="selectAll"></th> 
    <th rowspan="2">1</th>
    <th rowspan="2">2</th>
    <th colspan="3">3</th>
    <th colspan="3">4</th>
   </tr>	
   <tr>
    <th>x</th>
    <th>y</th>
    <th>z</th>
    <th>x</th>
    <th>y</th>
    <th>z</th>
   </tr>				   
</table>  
//其他行通过js中的appendto动态添加

js:

  var num=5;
  for (var i=0;i<num;i++)
  {
        var tab= $('<tr id="data'+i+'" οnclick="data_onclick(this)">'
              +'<td>'
              +'<input type="checkbox" id="box'+i+'" οnclick="update()"'    
              + (i==0?"checked":"") +'>'
              +'</td>'        
              +'<td class="info">1</td>'
              +'<td class="info">2</td>'  
              +'<td class="info">3</td>'
              +'<td class="info">4</td>'
              +'<td class="info">5</td>'
              +'<td class="info">6</td>'
              +'<td class="info">7</td>'
              +'<td class="info">8</td>'
              +'</tr>')
        tab.appendTo('#mytable');
  }

function data_onclick(obj)
{
	var obj_input=obj.firstChild.firstChild; //进入每一行的input节点
	//alert(obj_input.id);
	var checkbox=document.getElementById(obj_input.id);//链接到input的id
	if(checkbox.checked)//判断checkbox的状态
	{
		checkbox.checked = false;	
	}
	else
	{
		checkbox.checked = true;
	}
	update();
}

function update(){
  $("input[type='checkbox']").click(function(e){  
        e.stopPropagation();   
  });  //点击checkbox后防止tr的点击事件也被触发;
  
  $(':checkbox:not(:checked)').each(function(){  //对于未被选中checkbox的行
       var par_node=document.getElementById(this.id).parentNode.parentNode;//这里的this代表input元素(节点),向上追述两个父级即可进入tr元素
       document.getElementById(par_node.id).style.background="";//控制tr的背景色
  });

  $(':checkbox:checked').each(function(){
       var par_node=document.getElementById(this.id).parentNode.parentNode;
       document.getElementById(par_node.id).style.background="yellow";
  });
} 


  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值