有人可以帮我修改这个JQuery代码,以便它进行减法计算而不是添加吗?
在这个当前代码中,第一个表只是一个保存数据的普通表,第二个表是用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> </TD>
<TD id=weights> </TD>
<TD id=benchpresses> </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 :(得分:2)
这是一个具有起始值并从中减去的示例:
//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);
答案 1 :(得分:0)
我认为这就像将-=
更改为+=
答案 2 :(得分:0)
嗯,它没有添加值。它的作用是:
ages = 0 - 500 - 100 - 100 = -700
所以这是一个正确的减法。