Javascript 更改 table 单元格的 src

Javascript change the src of a table cell

我正在尝试将行的第一个单元格的内容更改为一些图像。下面是我的 Javascript 代码,它不起作用。我尝试使用 p.appendChild(img),但由于它在 for 循环中,每次我按下调用它的按钮时,它都会将另一个图像附加到该行。我估计我没有正确使用 .src?有人可以帮忙吗?

    var rowx =document.getElementById(rowid); //the row that I want to change its first cell
    var uri= "baseuri"+rowid;
    img = document.createElement('img');
    img.src= uri;
    var p = rowx.cells[0];
    p.src=img; //this doesn't change the first cell's content.if I use p.appendChild(img) it will append new img each time it gets executed. 

你不需要创建另一个图像,你可以简单地改变当前图像的src 属性:

rowx.cells[0].querySelector('img').src = uri;

如果图像是单元格内唯一的(或第一个)元素,您可以使用 firstElementChild,甚至更好:

rowx.cells[0].firstElementChild.src = uri;

参考文献:querySelector and firstElementChild .

cells 为您提供 td 元素的 HTMLCollection,它不支持 source 属性。如果您想编辑内容,您需要附加或修改其 innerHTML,例如

rowx.cells[0].innerHTML="";
rowx.cells[0].appendChild(img);