Javascript 将td元素添加到id为的tr

Javascript 将td元素添加到id为的tr,javascript,html,Javascript,Html,和标题差不多。我有html文档和 <table> <tr> <td id="1"></td> </tr> </table> 设置并希望javascript函数在前一个函数下添加,使其看起来像 <table> <tr> <td id="1"></td> <td id="2"></td> </tr>

和标题差不多。我有html文档和

<table>
  <tr>
    <td id="1"></td>
  </tr>
</table>

设置并希望javascript函数在前一个函数下添加
,使其看起来像

<table>
  <tr>
    <td id="1"></td>
    <td id="2"></td>
  </tr>
</table>

使用JQuery
.append()
方法

$('tr').append('<td>content</td>').attr('id', '2');
$('tr').append('content').attr('id','2');

演示:

对于这样简单的事情,不需要使用jQuery,请执行以下操作:

var tbl = document.querySelector("table");
var row0 = tbl.rows[0];

然后插入您的单元格:

var cell1=row0.insertCell(1);//the 1 here is the cell index
cell1.id="2";
为了管理DOM元素,我通常使用本机JavaScript编写代码,而不是使用jQuery或任何其他JavaScript框架。

使用jQuery:

$(document).ready(function(){

   $('#1').parent().append('<td id="2">2</td>');

}); 
$(文档).ready(函数(){
$('#1').parent().append('2');
}); 
用于将新单元格插入表行的javascript(纯)方法

使用insertCell()在表行末尾插入内容为的新单元格:

您还可以使用Javascript:

更新:

HTML:

<table>
  <tr id="myrow">
    <td id="1">Hello</td>
  </tr>
    <tr>
    <td id="1">Hello</td>
  </tr>
    <tr>
    <td id="1">Hello</td>
  </tr>
</table>
函数addField(){
var myTable=document.getElementById(“myTable”);
var currentIndex=myTable.rows.length;
var currentRow=myTable.insertRow(-1);
var a;
var currentCell=currentRow.insertCell(-1);
currentCell.style.height=“25px”;
currentCell.style.width=“20px”;
globalCheck=globalCheck+1;
currentCell.innerHTML=“”;

使用整数作为ID是不明智的,以[a-Za-z]的字母开头,然后是数字或其他字符。我认为按索引工作不是一个好主意。如果他有一行在this上面,有索引呢?或者如果他不知道哪一行是ID为td的?更好的方法是使用td的ID,以获取父元素(tr)还有添加新的td。是的,你是对的,但这里我只介绍了OP要求。请查看更新的答案。。@IshanJain,我收到ajax的回复,我们可以添加到tr吗?不要只发布代码。尤其是这么多。试着将你的答案集中在最低限度上。
var row = document.getElementsByTagName("tr")[0];
var x = row.insertCell(-1);
x.innerHTML="New cell";
var parenttbl = document.getElementsByTagName("tr");
var newel = document.createElement('td');
var elementid = document.getElementsByTagName("td").length
newel.setAttribute('id',elementid);
newel.innerHTML = "New Inserted"
parenttbl[0].appendChild(newel);
<table>
  <tr id="myrow">
    <td id="1">Hello</td>
  </tr>
    <tr>
    <td id="1">Hello</td>
  </tr>
    <tr>
    <td id="1">Hello</td>
  </tr>
</table>
var parenttbl = document.getElementById("myrow");
var newel = document.createElement('td');
var elementid = document.getElementsByTagName("td").length
newel.setAttribute('id',elementid);
newel.innerHTML = "New Inserted"
parenttbl.appendChild(newel);
 function addField () {

        var myTable = document.getElementById("myTable");
        var currentIndex = myTable.rows.length;

        var currentRow = myTable.insertRow(-1);

        var a ;
        var currentCell= currentRow.insertCell(-1);
        currentCell.style.height="25px";
        currentCell.style.width="20px";
        globalCheck=globalCheck+1;
        currentCell.innerHTML="<input id=\"check"+globalCheck+"\" type=\"checkbox\"></input>";