2011-10-19 44 views
0

任何人都可以幫助我改變這個JQuery代碼,以便它可以進行減法計算而不是加法運算嗎?JQuery Addition中的計算與減法

在這個當前代碼中,第一個表只是一個保存數據的普通表,第二個表是使用jQuery動態填充列的。我不知道如何完成相同的功能,只是在列中進行減法。我嘗試替換+ = by - =,它仍然添加值,但在它們前面放置了一個減號。例如,年齡欄的年齡值爲500,100,100和-700。

任何人都可以借鑑任何見解嗎?

<html> 
<head> 
<script type="text/javascript" SRC="https://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.js"></script> 

</head> 
<TABLE class=custom id=data> 
<TBODY> 
<TR> 
    <TH>name</TH> 
    <TH>age</TH> 
    <TH>weight</TH> 
    <TH>benchpress</TH> 
</TR> 
<TR> 
    <TD>stan</TD> 
    <TD>500</TD> 
    <TD>400</TD> 
    <TD>300</TD> 
</TR> 
<TR> 
    <TD>rj</TD> 
    <TD>100</TD> 
    <TD>50</TD> 
    <TD>50</TD> 
</TR> 
<TR> 
    <TD>jose</TD> 
    <TD>100</TD> 
    <TD>50</TD> 
    <TD>50</TD> 
</TR> 
</TBODY> 
</TABLE> 
<BR> 
<TABLE class=custom> 
<TBODY> 
<TR> 
<TH>ages</TH> 
<TH>weights</TH> 
<TH>benchpresses</TH> 
</TR> 
<TR> 
<TD id=ages>&nbsp;</TD> 
<TD id=weights>&nbsp;</TD> 
<TD id=benchpresses>&nbsp;</TD> 
</TR> 
</TBODY> 
</TABLE> 
<script type="text/javascript"> 

//these will hold the totals 
var ages = 0; 
var weights = 0; 
var benchpresses = 0; 

//reference the rows you want to add 
//this will not include the header row 
var rows = $("#data tr:gt(0)"); 
rows.children("td:nth-child(2)").each(function() { 
//each time we add the cell to the total 
ages -= parseInt($(this).text(),10); 
}); 
rows.children("td:nth-child(3)").each(function() { 
weights -= parseInt($(this).text(),10); 
}); 
rows.children("td:nth-child(4)").each(function() { 
benchpresses -= parseInt($(this).text(),10); 
}); 

//then output them to the elements 
$("#ages").html(ages); 
$("#weights").html(weights); 
$("#benchpresses").html(benchpresses); 

</script> 
</html> 
+0

你期望返回到? 0 - 500 -100 -100是-700? – Patricia

+0

你想要減去什麼?你的期望值是多少? – freakish

+0

所以你想要第一行從他們減去其餘的行?你想要什麼? – Hogan

回答

2

這裏是具有初始值並從減去的例子:

http://jsfiddle.net/nq8Nh/

//these will hold the totals 
var ages = 0; 
var weights = 0; 
var benchpresses = 0; 

// first row is starting value. 
var row1 = $("#data tr:eq(1)"); 
ages = parseInt(row1.children("td:nth-child(2)").text()); 
weights = parseInt(row1.children("td:nth-child(3)").text()); 
benchpresses = parseInt(row1.children("td:nth-child(4)").text()); 

//reference the rows you want to add 
//this will not include the header row or first row 
var rows = $("#data tr:gt(1)"); 
rows.children("td:nth-child(2)").each(function() { 
//each time we add the cell to the total 
ages -= parseInt($(this).text(),10); 
}); 
rows.children("td:nth-child(3)").each(function() { 
weights -= parseInt($(this).text(),10); 
}); 
rows.children("td:nth-child(4)").each(function() { 
benchpresses -= parseInt($(this).text(),10); 
}); 

//then output them to the elements 
$("#ages").html(ages); 
$("#weights").html(weights); 
$("#benchpresses").html(benchpresses); 
0

我認爲這是爲改變-=+=

0

那麼,它不會添加值一樣簡單。它所做的是:

ages = 0 - 500 - 100 - 100 = -700 

所以這是一個正確的減法。