简体   繁体   English

Javascript:使用数组中的图像填充表格

[英]Javascript: Populating a table with images from an array

I'm trying to create a javascript table with rows of 10 from an array of images but with no luck. 我正在尝试创建一个javascript表,其中包含来自图像数组的10行,但是没有运气。 The table works but each cell just has [object HTMLImageElement] instead of the image. 该表有效,但是每个单元格仅具有[object HTMLImageElement]而不是图像。

The code I tried is below. 我尝试过的代码如下。

for(var i=0; i<myArray.length; i++){
    myArray[i] = new Image();
    myArray[i].src = i + '.gif'; 
}

document.writeln('<table border = 1 >');
for(var j=0; j<myArray.length; j++){
    if(j%10==0 && j!==0){
    document.writeln('</tr><tr>');
    }
    document.writeln('<td >' + myArray[j] + '</td>');
}
document.writeln('</tr></table>');

Look at those two lines from your code: 查看代码中的这两行:

myArray[i] = new Image();

document.writeln('<td >' + myArray[j] + '</td>'); // wrong - myArray has to be a string

So, myArray is an image , but in the second line you're trying to make it a string - "<td>" + myArray[j] + "<td>" - this is a way to concatenate strings, not objects. 因此,myArray是一个图像 ,但是在第二行中,您尝试将其设置为字符串- "<td>" + myArray[j] + "<td>" -这是一种连接字符串而不是对象的方法。 (in this case, myArray[i] is implicitly converted to a string - "htmlImageElement" or whatever) (在这种情况下,myArray [i]被隐式转换为字符串-“ htmlImageElement”或其他内容)

What you need is to display an <img> tag with the src attribute set to the one in myArray[i], ie: 您需要显示一个<img>标记,其src属性在myArray [i]中设置为一个,即:

document.writeln('<td ><img src="' + myArray[j].src + '" /></td>');

One way to do this is this: 一种方法是这样的:

$(document.createElement('table'));
var result = "";
for (let i = 0; i < myArray.length; i++){
    result+= '<tr><td><img src="' + myArray[i] + '" alt=""/></td></tr>'
}
$('#table').append(result);

Or this: 或这个:

$(document.createElement('table'));
var result = "";
myArray.map(function(item){
    result+= '<tr><td><img src="' + item + '" alt=""/></td></tr>'
})
$('#table').append(result);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM