javascript - 使用 jquery 循环遍历表行并通过类名访问数据

标签 javascript jquery html

我有以下表格格式。这些行是使用两个 for 循环生成的:

<table id="tableMain">
    <tr id = "uniqueID1" class = "firstClass">
        <td><input type='radio' name='radio1' value='0' class='myradio'>"</td>
        <td><input type='radio' name='radio1' value='1' class='myradio'>"</td>
    </tr>

    <tr id = "uniqueID2" class = "secondClass">
        <td><input type='radio' name='radio2' value='2' class='myradio1'>"</td>
        <td><input type='radio' name='radio2' value='3' class='myradio1'>"</td>
        <td><input type='radio' name='radio2' value='4' class='myradio1'>"</td>
    </tr>

    <tr id = "uniqueID3" class = "thirdClass">
        <td><input type='radio' name='radio3' value='5' class='myradio2'>"</td>
        <td><input type='radio' name='radio3' value='6' class='myradio2'>"</td>
        <td><input type='radio' name='radio3' value='7' class='myradio2'>"</td>
        <td><input type='radio' name='radio3' value='8' class='myradio2'>"</td>
    </tr>
</table>

基本上,整个表中每一行的 tr ID 都是唯一的,但每次循环退出内循环时,类名都不同。因此,它在表内创建了一种组,但 rowsID 仍然是唯一的。

我的问题是如何根据类名访问每行的选定值并获取每行的值。

这是我尝试过的:

$('#button').click(function(){
var rows=[];
$('#myForm tr').each(function(){
    var id=$(this).data('id');
    if( rows.indexOf(id) ==-1){ /* push to array if it doesn't exist */
        rows.push( id);
    }
});
var totalUnique= rows.length;
alert("Total Number of Comparison = " + totalUnique);
});

有没有办法将每个“类”结果提取到数组中,对结果执行某些操作,然后对其余的执行相同的操作..?即输入表体n查找第一类,循环并获取每行上的选定值,然后对其余部分执行相同的操作?

最佳答案

对于您的第二个问题,这里是获取每个 tr 行的值的代码:

DEMO HERE

function rowsValues(){
 $("#tableMain tr").each(function(index,value){
    var rowValues=new Array(); 
    $(this).find('input:radio:checked').each(function(){
    rowValues.push(parseInt($(this).val()));
   }) 
      alert("row"+index+" : "+rowValues);
     //do something with rowValues
 } 
)}

要得到总和,试试这个 DEMO

function SUM(){
    var sum=0;
    $("#tableMain").find('input:radio:checked').each(function(){sum+= parseInt($(this).val());});
    return sum;
}

$("#btn").click(function(){alert(SUM());});

PS:关闭您的<td></td>正确

关于javascript - 使用 jquery 循环遍历表行并通过类名访问数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20532566/

相关文章:

javascript - JQuery - 如何重用 JSON 数据?

javascript - 获取错误 : 'Cannot assign to ' location' because it is a constant or a read-only property' with mailto function in Angular app

javascript - 使用 Ajax 将数组从 javascript 发送到 php 函数

jQuery、Bootstrap 单击删除选项卡

jquery - 灰色提交按钮直到表格填写完毕

html - CSS不正确的元素高度

javascript - Bootstrap 导航栏切换按钮不折叠

javascript - Ajax 从 C++ http 服务器断开连接

javascript - Jquery:获取 parent 的 parent

javascript - 使用 jQuery/JavaScript 做出答案后删除文本