首页 > 解决方案 > 遍历 JSON 并获取每个数据键的图像

问题描述

我有这张桌子

<table id="player_info">
<tr>
<th>Position</th>
<th>Club</th>
<th>Points</th>
<th>Matches Played</th>
<th>Wins</th>
<th>Draws</th>
<th>Losses</th>
<th>Goals For</th>
<th>Goals Against</th>
<th>Goal Difference</th>
<th>Form</th>
</tr>
</table>

我有这个函数,它遍历 JSON 键并使用每个键创建一个新的表格单元格。我想让每个俱乐部的徽标出现在表格单元格中的名称旁边。徽标 URL 存储在 JSON 中。

我当前的代码

data.api.standings[0].forEach(elements => {

        var tr = document.createElement('tr');

        var img = new Image();

        img.src = elements.logo;

        tr.innerHTML = '<td>' + elements.rank + '</td>' + 
                       '<td>' + elements.teamName +  img + '</td>' + 
                       '<td>' + elements.points + '</td>' + 
                       '<td>' + elements.all.matchsPlayed + '</td>' + 
                       '<td>' + elements.all.win + '</td>' + 
                       '<td>' + elements.all.draw + '</td>' + 
                    '<td>' + elements.all.lose + '</td>' + 
                    '<td>' + elements.all.goalsFor + '</td>' + 
                    '<td>' + elements.all.goalsAgainst + '</td>' + 
                    '<td>' + elements.goalsDiff + '</td>' + 
                    '<td>' + elements.forme + '</td>';

        table.appendChild(tr);

    });

但是我得到了团队名称和 [object HTMLImageElement] 并且没有图像。

标签: javascript

解决方案


在你的情况下,你可以这样做

var img = '<img src="' + elements.logo + '" />'

而不是制作一个 img 元素


推荐阅读