2013-02-14 41 views
0

我正在循環一組動態表格行,我試圖捕獲每個表格行中使用jquery的cell2的值,但它每次都返回cell2 row1的值,甚至雖然它每次都能識別單元格1的正確行值,但有誰能告訴我我錯了嗎?見下面的示例代碼。爲jQuery中的每個表格計算文本框

感謝您收到的任何幫助。

//html 
<table class=plantTable> 
<tr> 
<td><input type=text value=0 class=cell1></td> 
<td><input type=text value=0 class=cell2></td> 
<td><input type=text value=0 class=cell3></td> 
</tr> 
<tr> 
<td><input type=text value=0 class=cell1></td> 
<td><input type=text value=0 class=cell2></td> 
<td><input type=text value=0 class=cell3></td> 
</tr> 
<tr> 
<td><input type=text value=0 class=cell1></td> 
<td><input type=text value=0 class=cell2></td> 
<td><input type=text value=0 class=cell3></td> 
</tr> 
</table> 

//jquery 
    tr = $(".plantTable tr").length; 

    $(tr).each(function() { 
     $(this).find($(".cell1").blur(function() { 
     cell1val = parseInt($(this).val()); 
     cell2val = parseInt($(".cell2").val()); //Returns the value of cell2 in the first row only? 
    })); 
+3

'tr'等於一個整數,'TR = $(「TR plantTable」)長度;' – 2013-02-14 16:01:35

+0

HTTP: //codepen.io/anon/pen/GCdpA – Shanimal 2013-02-14 16:18:30

回答

0

裏面找到你再次發現,它將查看從頂部的文件,從而找到row1 cell2。如果你希望你的當前項目的兄弟,你似乎,這樣做:

$("tr").each(function() { 
     $(this).find($(".cell1")).blur(function() { 
     cell1val = parseInt($(this).val()); 
     cell2val = parseInt($this.siblings(".cell2").val()); 
     }); 
    }); 

這將檢索小區2的值旁邊小區1目前發現的。

+1

你有一個支架不匹配。 – BenM 2013-02-14 16:05:20

+0

呃哇......其實很多事情都是錯的。謝謝本...所有複製粘貼。 – Spork 2013-02-14 16:29:29

+0

感謝Spork,嘗試了上述解決方案,但cell2 val返回NaN,這很奇怪,因爲它們具有數值。 – ullevi83 2013-02-15 10:06:11

0

你的jQuery應該是這樣的:

$('.plantTable tr').each(function() { 
    $(this).find('.cell1').blur(function() { 
     cell1val = parseInt($(this).val()); 
     cell2val = parseInt($(this).siblings(".cell2").val()); 
    }); 
}); 
+0

敢肯定你做同樣的事情:d $(本).find($(」小區1 「)模糊(函數(){ 與 $(本).find($(」 小區1。 「)0.blur(函數(){ 或最有可能實際上.find('。cell1')...... – Spork 2013-02-14 16:31:15

+0

良好的通話 - 我錯過了! – BenM 2013-02-14 16:32:41

+0

乾杯BenM,嘗試了上述解決方案,但仍然選擇cell2的第一行值,很奇怪,必須重新考慮。 – ullevi83 2013-02-15 09:52:09

0

關於解決方案,你的工作完美,但我懷疑他們時,一個新的元素被添加到它。下面的代碼將正常工作,即使其他一些輸入元件在未來添加..

// If you want to maintain resusable collection of all inputs inside 
var inputCollection = $([]).pushStack($("table.plantTable :input")); 
// Then do operations with inputCollection 
// Else, you could follow chaining like below 

$("table.plantTable").delegate("input", "blur", function() { 
    var inputs = $(this).closest('tr').find(':input'); 
    // do whatever you want to with inputs 
});