通过"finding"表中的属性来更新 jQuery 中的对象值



我正在尝试创建一个表格,该表格对另一个表中的值求和,同时按类别对其进行排序(第一个td对应于值,第三个td对应于排序元素(。

下面的代码是当前代码的示例 (https://jsfiddle.net/p476bqxf/16/(

var entries = [0,0];
$('#secondTable tr').each(function(){
switch ($(this).find("td:nth-child(3)").html()){
case "One":
entries[0] += parseInt($(this).find("td:first-child").html());
break;
case "Two":
entries[1] += parseInt($(this).find("td:first-child").html());
break;
default:
break;
}
});
$("#firstTable td").each(function(e){
$(this).html(entries[e]);
});

但是,为了避免重复的代码(因为有两个以上的排序元素(,我想使用 Object 而不是 Array,但我被语法卡住了。有关如何正确编写此代码的任何建议将不胜感激:

var entries = {
"One" : 0,
"Two": 0
};
$('#secondTable tr').each(function(){
var n = $(this).find("td:nth-child(3)").html();
entries.n += parseInt($(this).find("td:first-child").html());
//entries.n doesn't work, the idea is to match the value of
//every 3rd td with a property of the object...
});
$("#firstTable td").each(function(e){
$(this).html(entries[e]);
//entries[e] also doesn't work, since it's not an array
});

您需要使用[]对象表示法来访问具有变量名称的属性

然后对象没有保证的顺序,因此您需要一个属性名称数组来指定顺序

您可以执行以下操作:

var entries = {
"One": 0,
"Two": 0
};
$('#secondTable tr').each(function() {
var n = $(this).find("td:nth-child(3)").html();
entries[n] += parseInt($(this).find("td:first-child").html());
});
["One", "Two"].forEach(function(v, i) {
$("#firstTable td").eq(i).text(entries[v])
})
#firstTable {
background: green;
}
#secondTable {
background: grey;
}
table {
width: 150px;
text-align: center;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table id="firstTable">
<tr>
<td></td>
<td></td>
</tr>
</table>
<table id="secondTable">
<tr>
<td>10</td>
<td>Sthg</td>
<td>One</td>
</tr>
<tr>
<td>30</td>
<td>Sthg</td>
<td>Two</td>
</tr>
<tr>
<td>5</td>
<td>Sthg</td>
<td>One</td>
</tr>
</table>

最新更新