2012-01-31 58 views
0

我試圖在表中使用jQuery將一列中的值加起來。爲了實現這一點,我首先試圖找到每一行的第一個單元格,然後將它們添加在一起,然後將此值放入輸入字段中。jQuery:對於每一行第一個單元格

這樣做的最好方法是什麼?

到目前爲止,我有:

// for each row 
$('table tbody tr').each(function() { 

     $firstCell = $(this).index(1).find('input').val(); 

}); 

所以我需要添加的第一個單元在一起的每一行。所以基本上是每個創建的$ firstCell變量的實例。例如

$('output').val(parseInt($firstCell.val()) + parseInt($firstCell.val())); 

任何人都可以指向正確的方向嗎?

感謝

+0

http://stackoverflow.com/questions/6155293/select-第一,TD-中,每行-W-的jQuery – ygesher 2013-10-04 11:22:42

回答

1

JS:

$('table tbody tr').each(function() { 
    $firstCell = $('td:first-child', this).html(); 
}); 

上面的代碼將使用第一個TD元素的TR和返回的HTML(),只是爲了讓你知道TD沒有價值,它不是輸入字段也不選擇或textarea。

0

這樣的事情會做的,代碼是未經測試

編輯:根據最新的更改,我添加計數器

// array to hold all cell contents 
var firstCellContents = [], 
    cellCounter = 0; 

// for each row 
$('table tbody tr').each(function() { 

    var $firstCell = $(this).children('td').first(), 
     firstCellContent = $firstCell.text(); 

    firstCellContents.push(firstCellContent); 
    cellCounter += parseInt(firstCellContent, 10); // don't forget the 10! 

}); 

// add all fields to the inputfield: 
$('#inputField').val(firstCellContents.join(',')); 

// or add the total to the inputfield: 

$('#inputField').val(cellCounter); 
相關問題