我有以下代码
resultElement.innerHTML = '';
fetch(`https://countriesnode.herokuapp.com/v1/countries/`)
.then(resp => resp.json()) // transform the data into json - an array with all the element
.then(resp =>
resp.map(({continent,native,languages})=>({continent,native,languages})))
.then((resp) => {
for(var i = 0;i <resp.length;i++){
console.log(resp[i].continent,resp[i].native,resp[i].languages);
resultElement.innerHTML = '<h5>Continent:</h5>' +
'<pre>' + (resp[i].continent, '\t') + '</pre>' + ' ' +
'<h5>Native:</h5>' +
'<pre>' + (resp[i].native, '\t') + '</pre>';
}
}
)
}
在上面的代码中,htmlString仅显示h5标记,但内部没有任何值。我想显示标记内的所有数组值。不幸的是,它没有用,我找不到适合的解决方案。但是它显示在控制台中。
最佳答案
不要将逗号用作(resp[i].continent, '\t')
,因为它只会返回\t
,而是连接:(resp[i].native + '\t')
。另外,您需要将HTML标记与+=
连接起来,而不是分配给它:
resultElement.innerHTML = '';
fetch(`https://countriesnode.herokuapp.com/v1/countries/`)
.then(resp => resp.json()) // transform the data into json - an array with all the element
.then(resp => resp.map(({ continent, native, languages }) => ({ continent, native, languages })))
.then((resp) => {
for (var i = 0; i < resp.length; i++) {
//console.log(resp[i].continent, resp[i].native, resp[i].languages);
resultElement.innerHTML += '<h5>Continent:</h5>' + '<pre>' + (resp[i].continent + '\t') + '</pre>' + ' ' + '<h5>Native:</h5>' + '<pre>' + (resp[i].native + '\t') + '</pre>';
}
})
<div id="resultElement"></div>
表格实现:
resultElement.innerHTML = '';
fetch(`https://countriesnode.herokuapp.com/v1/countries/`)
.then(resp => resp.json()) // transform the data into json - an array with all the element
.then(resp => resp.map(({ continent, native, languages }) => ({ continent, native, languages })))
.then((resp) => {
for (var i = 0; i < resp.length; i++) {
//console.log(resp[i].continent, resp[i].native, resp[i].languages);
resultElement.innerHTML +='<tr><td>' + (resp[i].continent + '\t') + '</td>' + '<td>' + (resp[i].native + '\t') + '</td>';
}
})
<table>
<thead>
<tr>
<td>Continent</td>
<td>Native</td>
</tr>
</thead>
<tbody id="resultElement"></tbody>
</table>
关于javascript - 如何在html字符串中传递javascript数组值以更改innerHTML,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/58165608/