如何在表中插入图像



我需要创建一个行

的表

ID |图像|图像信息

是代码的一部分:

function add(form) {
table1 = getElementById('mytable');
row1 = table1.insertRow(table1.rows.length);
cell1 = row1.insertCell(row1.cell.length);
cell1 = row1.rowIndex;
}
<table id="mytable" border="1">
<tr>
<th>id</th>
<th>picture</th>
<th>info</th>
</tr>
</table>
<br>
<form>
<input type="text" name="info">
<input type="file" name="pic" accept="image/png, image/jpeg">
<input type="button" onclick="add(this.form)" value="Add" /> <br>
<input type="button" onclick="del(this.form)" value="Delete" />
</form>

我只编码ID。现在我需要插入图片。我不知道该怎么做……

p。S:我是初学者,正在为大学实习

它应该是这样工作的,虽然没有测试(我粉碎了你的函数中的一些其他错误):

function add(form) {
table1 = document.getElementById('mytable');
row1 = table1.insertRow(table1.rows.length);
cell1 = row1.insertCell(row1.cells.length);
cell1 = row1.rowIndex;
cell2 = row1.insertCell(row1.cells.length);
let file = document.getElementsByName('pic')[0].files[0];
let src = URL.createObjectURL(file);
let image = document.createElement('img');
image.src = src;
cell2.appendChild(image);
// ...
}

参考:https://developer.mozilla.org/en-US/docs/Web/API/URL/createObjectURL

使用图片地址上传图片的一种方法如下:你可以尝试使用网络上的任何图像地址(例如:https://static.thenounproject.com/png/802538-200.png)

如果使用来自用户本地磁盘的映像,由于安全风险,您可能会得到net::ERR_UNKNOWN_URL_SCHEME。

HTML

<table id="mytable" border="1">
<tr>
<th>id</th>
<th>picture</th>
<th>info</th>
</tr>
</table>
<br>
<form>
<label for="id">Id</label>
<input type="text" name="id" id="id">
<label for="pic">Picture Path</label>
<input type="text" name="pic" id="pic">
<label for="info">Info</label>  
<input type="text" name="info" id="info">
<input type="button" onclick="add(this.form)" value="Add" /> 
</form>

JS

function add() {
let table = document.getElementById('mytable');
let row = table.insertRow(0);
let cell0 = row.insertCell(0);
let cell1 = row.insertCell(1);
let cell2 = row.insertCell(2);
let source = document.getElementById('pic').value;
let img = document.createElement('img');
img.setAttribute('src', source);
cell0.innerHTML = document.getElementById('id').value;
cell1.appendChild(img);
cell2.innerHTML = document.getElementById('info').value;
}

最新更新