gpt4 book ai didi

javascript - 从函数生成模板文字的正确方法

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

我有一个函数,它接受 id 参数并返回模板文字:

const template = (id) => {
return `<div style="box-sizing: border-box; height: 32px; border-bottom: 1px solid #ECECEC; color: #282828; padding: 8px; display: flex; align-items: center;">
<div style="padding-right: 8px; margin-top: 8px;">
[Image id=`${id}` align="style"] /* CMS specific code, just for clarification */
</div>
<div style="">
<h2 style="font-size: 14px;">Champions League</h2>
</div>
</div>`
}

还有一个包含一堆 ID 的数组:

const cmsImgIds = [448, 449, 450, 451, 452, 453, 454]  

我循环遍历 cmsImgIds 并将模板写入文档:

  for (element in cmsImgIds) {
console.log(element, 'element')
document.getElementById('root').innerHTML = template(element)
}

我预计每个模板都会被写入文档 7 次。

我在这里做错了什么?

window.onload = function(){  

const cmsImgIds = [448, 449, 450, 451, 452, 453, 454]

const template = (id) => {
return `<div style="box-sizing: border-box; height: 32px; border-bottom: 1px solid #ECECEC; color: #282828; padding: 8px; display: flex; align-items: center;">
<div style="padding-right: 8px; margin-top: 8px;">
[Image id="${id}" align="style"]
</div>
<div style="">
<h2 style="font-size: 14px;">Champions League</h2>
</div>
</div>`
}

for (element in cmsImgIds) {
console.log(element, 'element')
document.getElementById('root').innerHTML += template(element)
}

}
<div id="root"></div>

最佳答案

这里它将替换 for 中每个循环的innerHTML,那么你将只有最后一个元素,你应该做的是:

document.getElementById('root').appendChild(template(element))

抱歉,如果模板是 HTMLElement,就会出现这种情况

你可以在for中生成一个大字符串,然后将其设置为innerHTML

let html = '';
for (element in cmsImgIds) {
console.log(element, 'element')
html = html + template(element)
}
document.getElementById('root').innerHTML = html

关于javascript - 从函数生成模板文字的正确方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59196991/

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