我的HTML结构如下:
<button type="button">Add Column Record</button>
<table border="1">
<tr>
<th> Header 1</th>
<td> L1</td>
<td> L1</td>
</tr>
<tr>
<th> Header 2</th>
<td> L2 </td>
<td> L2 </td>
</tr>
<tr>
<th> Header 3</th>
<td> L3</td>
<td> L3</td>
</tr>
按下按钮后,我想在最右边的列中添加垂直记录。我应该如何使用jQuery实现这种效果?
答案 0 :(得分:2)
您可以尝试这样的事情:
$('button').on('click', function() {
var table = $('table');
var newCell = null;
table.find('tr').each(function(index) {
newCell = $('<td/>');
newCell.text('L' + (index+1));
$(this).append(newCell);
});
});
答案 1 :(得分:1)
检查一下:http://jsfiddle.net/MMXnY/1/
$('button').click(function(){
$('table tr').each(function(i, v){
$(this).append($('td:last',this).clone().text('L'+parseInt(i+1)));
});
});
您可以遍历每个tr
,然后make a clone of the last td and then put text and increase the number by parsing it then append it after last td.
答案 2 :(得分:0)
http://api.jquery.com/appendTo/
http://api.jquery.com/prepend/
每个函数的追加略有不同。阅读它们,找出你想要使用的是什么。
示例:
在
<div class="area"></div>
SCRIPT
$('<p>Test</p>').appendTo('.area');
在
<div class="area"><p>Test</p></div>
希望这有帮助!
答案 3 :(得分:0)
如果您想添加一列,则可以对表格的每个tr
进行迭代,然后添加新的td
示例:
$("#id_of_your_table > tbody > tr").each(function(index, trElement) {
// Add a new TD at the end
$(trElement).append($(document.createElement("td")));
});
注意:不要忘记在tbody
中添加table
以获得良好的行为(如果不存在,某些浏览器会默认添加它)
示例:
<table id="myTable">
<tbody>
<tr>
.....
这是一个完整的例子:
<button id="addColumn">Add new column</button>
<table id="myTable">
<tbody>
<tr>
<td>col 1</td>
<td>col 2</td>
<td>col 3</td>
</tr>
<tr>
<td> col 1</td>
<td> col 2</td>
<td> col 3</td>
</tr>
</tbody>
</table>
<script>
// When DOM is ready
$(document).ready(function() {
// Listen on the click on the button
$("#addColumn").on('click', function(mouseEvent) {
// Iterate on all TR of the table
$("#id_of_your_table > tbody > tr").each(function(index, trElement) {
// Add a new TD at the end
$(trElement).append($(document.createElement("td")));
});
});
});
</script>