Html 在Javascript中将图像插入表格单元格

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16978296/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-29 09:11:30  来源:igfitidea点击:

Insert image into table cell in Javascript

javascripthtmlimagehtml-tablecell

提问by user2462483

I want to insert images to the new cell just created. How can I do it? Can anyone guide me in doing it? Here's my code to insertcells:

我想将图像插入刚刚创建的新单元格。我该怎么做?任何人都可以指导我这样做吗?这是我插入单元格的代码:

<!DOCTYPE html>
<html>
<head>
<script>
function displayResult()
{
var firstRow=document.getElementById("myTable").rows[0];
var x=firstRow.insertCell(-1);
x.innerHTML="New cell"
}
</script>
</head>
<body>

<table id="myTable" border="1">
  <tr>
    <td>First cell</td>
    <td>Second cell</td>
    <td>Third cell</td>
  </tr>
</table>
<br>
<button type="button" onclick="displayResult()">Insert cell</button>

</body>
</html>

All I want is to insert image in the cell created.

我想要的只是在创建的单元格中插入图像。

回答by MrCode

You can create the image element and append it to the new cell:

您可以创建图像元素并将其附加到新单元格:

function displayResult()
{
    var firstRow=document.getElementById("myTable").rows[0];
    var x=firstRow.insertCell(-1);
    x.innerHTML="New cell";

    var img = document.createElement('img');
    img.src = "link to image here";
    x.appendChild(img);
}

Beware of building the raw HTML for the image, if you do it that way you'll need to make sure that you escape the srcand any other attributes.

当心为图像构建原始 HTML,如果你这样做,你需要确保你转义src和任何其他属性。

回答by p e p

Simply set the inner HTML of the new cell to the HTML of an img element, with whatever src or attributes you wish.

只需将新单元格的内部 HTML 设置为 img 元素的 HTML,使用您希望的任何 src 或属性。

function displayResult()
{
    var firstRow=document.getElementById("myTable").rows[0];
    var x=firstRow.insertCell(-1);
    x.innerHTML="<img src='myImageURL' alt='hello'/>";
}

回答by user2462483

 function displayResult()
    {
   document.getElementById("myTable").rows[0].innerHTML="your image";
    }

may be this can help,dynamicism can be achieved later on,just try if it works for now?

可能这会有所帮助,稍后可以实现动态主义,试试现在是否有效?