我有一个表,需要用动态生成的字典键值pair.The替换每一行的最后一列,下面是我的表结构,
<table id="example">
<tr>
<td>Title</td>
<td>T1</td>
</tr>
<tr>
<td>Description</td>
<td>D1</td>
</tr>
</table>
我想在每一行的末尾追加另一列。就像这样,
<table id="example">
<tbody>
<tr>
<td>Title</td>
<td>T1</td>
<td>T2</td>
</tr>
<tr>
<td>Description</td>
<td>D1</td>
<td>D2</td>
</tr>
</tbody>
</table>
我随身带着这个信息
var dict ={ "t1":"T2","t2":"D2“}我将如何使用JQuery来实现它?
发布于 2017-06-18 08:34:02
它可以使用以下代码来实现,
var dict = {
"t1": "T2",
"t2": "D2"
}
var count = 0;
$.each (dict, function (field, value) {
$('#example tr').each(function() {
if($("tr").index(this) == count){
$(this).find('td:last').after('<td>' + value + '</td>');
}
});
count++;
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<table id="example">
<tr>
<td>Title</td>
<td>T1</td>
</tr>
<tr>
<td>Description</td>
<td>D1</td>
</tr>
发布于 2017-06-18 08:35:36
使用以下代码:
// append the <td> inside each found <tr> in the table
$("#example > tr").each(function(index){
$(this).append("<td>" + value[index] + "</td>");
});
发布于 2017-06-18 11:17:39
您可以使用last()
函数在每个tr
中获得最后一个td
,方法是使用如下所示的jQuery选择器:
var dict = {
"t1": "T2",
"t2": "D2"
}
var index = 0;
function start() {
var x = $('#example tr')
for (i = 0; i < x.length; i++) {
row = x[i]
var valInDic = index == 0 ? dict.t1 : dict.t2;
index++;
$(row).append('<td>' + valInDic + '</td>')
if (index == 2)
index = 0;
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table id="example">
<tbody>
<tr>
<td>Title</td>
<td>T1</td>
</tr>
<tr>
<td>Description</td>
<td>D1</td>
</tr>
</tbody>
</table>
<button onclick=start() ">Start</button>
我希望这会有所帮助;)
https://stackoverflow.com/questions/44613120
复制相似问题