jquery如何获取checkbox在table中对应的行数 求代码

如题所述

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>获取checkbox在table中对应的行数</title>
<style type="text/css">
*{margin:0;padding:0}
.tables{width:500px;background: #f0f0f0;margin:50px auto;font:12px/21px Arial, Helvetica, sans-serif}
.tables td{border: 2px solid #fff}
</style>
</head>
<body>
<table class="tables">
<caption>获取checkbox在table中对应的行数</caption>
<tr>
<td><input type="checkbox" class="chk" /> </td>
</tr>
<tr>
<td><input type="checkbox" class="chk" /> </td>
</tr>
<tr>
<td><input type="checkbox" class="chk" /> </td>
</tr>
<tr>
<td><input type="checkbox" class="chk" /> </td>
</tr>
<tr>
<td><input type="checkbox" class="chk" /> </td>
</tr>
</table>
<script type="text/javascript" src="js/jquery.js"></script>
<script type="text/javascript">
var total_tr=$(".tables").find("tr"); //获得table中tr 的总行数
$(".tables").click(function(event){
event = window.event || event;
var target = event.target || event.srcElement;
if(target.type == "checkbox" && target.checked == true){
var this_tr=$(target).parent().parent();//获得当前点击的checkbox 所在tr
var index=total_tr.index(this_tr); //获取该tr在整个table中 位置
alert('此checkbox在table 中对应的行数是:'+index+' (这只是索引值)');
}
});
</script>
</body>
</html>追问

如何点击按钮后得到所有被选中的行数呢

追答

一样的嘛.....

追问

已经有人给我讲解了 没有你那么复杂 谢谢了

温馨提示:内容为网友见解,仅供参考
第1个回答  2013-05-15
你好, 你要得到行数和列数也不难,我简单的写了下
html代码:
<table border="1" width="160px">
<tr>
<td>时间段</td>
<td>1</td>
<td>2</td>
<td>3</td>
<td>4</td>
</tr>
<tr value="row1" class="rowvalue">
<td>星期一</td>
<td><input type="checkbox" class="option"></td>
<td><input type="checkbox" class="option"></td>
<td><input type="checkbox" class="option"></td>
<td><input type="checkbox" class="option"></td>
</tr>
<tr value="row2" class="rowvalue">
<td>星期二</td>
<td><input type="checkbox" class="option"></td>
<td><input type="checkbox" class="option"></td>
<td><input type="checkbox" class="option"></td>
<td><input type="checkbox" class="option"></td>
</tr>
<tr value="row3" class="rowvalue">
<td>星期三</td>
<td><input type="checkbox" class="option"></td>
<td><input type="checkbox" class="option"></td>
<td><input type="checkbox" class="option"></td>
<td><input type="checkbox" class="option"></td>
</tr>
</table>
js代码:
$(function(){

$(".option").click(function(){
var arr = [];
$(".option").each(function(colindex){
if($(this).is(":checked"))
{
if(colindex % 4 == 3)
{
arr.push(Math.floor(colindex/4) + 1);
arr.push(4);
}else{
arr.push(Math.floor(colindex/4) + 1);
arr.push((colindex+1) % 4);
}
alert(arr);
return false;
}
})
})

})
已经测试过了,希望你可以看下这个思路,望对你有所帮助吧.本回答被网友采纳
第2个回答  推荐于2016-06-09

    获取table下所有tr     var trs = $("#tableID tr")

    获取table下的所有tr    

      循环所有tr 获取tr下所有的td   看看你的checkbox在第几列  比如在第一列:

      for(int i ,i<trs.length,i++){

      $(trs).find(td).eq(0)

      }

      我不知道你说的行数是什么意思  但是这个可以获取所有的checkbox

相似回答