[英]What is wrong with my dynamic append td in jquery/javascript?
I have a table where each row contains two elements: 我有一个表,其中每行包含两个元素:
<table>
<tr><td>A</td><td>B</td></tr>
<tr><td>C</td></tr>
</table>
I am trying to append a cell with "D" into the last row (the 2nd row that is already there in the current table), but am having difficulty. 我试图将一个带有“D”的单元格附加到最后一行(当前表中已经存在的第二行),但是我遇到了困难。
I tried to perform: 我试着表演:
$("table").children().get(1).append("<td>D</td>");
and 和
var elem = $("<td/>", {
text: 'D'
});
$("table").children().get(1).appendChild(elem);
and I get the error: 我收到错误:
Uncaught Error: NotFoundError: DOM Exception 8
Putting tbody in there does not work either: 把tbody放在那里也不起作用:
$("table tbody").children().get(1).appendChild(elem);
What is to proper way to do this? 这样做的正确方法是什么?
I do not want to depend on just the "last td" as assuming I had another element "E", I would want it to automatically add to a third row by itself as opposed to tacking it on as a third column at the end of the 2nd row. 我不想仅依赖于“最后一个td”,假设我有另一个元素“E”,我希望它自动添加到第三行,而不是将其作为第三列添加到结尾处。第二排。
Try: 尝试:
$("table td:last").after("<td>D</td>");
Results in the structure: 结果结果:
<table>
<tbody><tr><td>A</td><td>B</td></tr>
<tr><td>C</td><td>D</td></tr>
</tbody></table>
尝试这个:
$('<td>D</td>').appendTo('table tr:eq(1)');
you can append dynamically by finding next letter from existed letter.May be You need to modify as per your requirement. 您可以通过查找现有信件中的下一个字母动态追加。可能需要根据您的要求进行修改。
HTML HTML
<table>
<tr>
<td>A</td>
<td>B</td>
</tr>
<tr>
<td>C</td>
</tr>
</table><button type="button" id="addanother" >Add</button>
JS : JS:
$('#addanother').on('click',function(){
var length=$('table').find('td:last').parent().children().length;
var text=$('table').find('td:last').text();
var nextlet=nextLetter(text);
if(length == 2){
$('table').find('tr:last').after('<tr><td>'+nextlet+'</td></tr>');
}else if(length == 1){
$('table').find('td:last').after('<td>'+nextlet+'</td>');
}
});
// To get alphabets from A-Z from a-z
function nextLetter(s){
return s.replace(/([a-zA-Z])[^a-zA-Z]*$/, function(a){
var c= a.charCodeAt(0);
switch(c){
case 90: return 'A';
case 122: return 'a';
default: return String.fromCharCode(++c);
}
});
} }
Fiddler : http://jsfiddle.net/j98H7/1/ 提琴手: http : //jsfiddle.net/j98H7/1/
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.