gpt4 book ai didi

javascript - 如何在html字符串中传递javascript数组值以更改innerHTML

转载 作者:行者123 更新时间:2023-12-02 22:51:28 25 4
gpt4 key购买 nike

我有以下代码


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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com