简体   繁体   English

如何 append<li> 到每个数组?</li>

[英]How to append <li> to each array?

My head was overheated today.. I need help with my code.今天我的头过热了。我的代码需要帮助。 My English is not so good, so it's hard to explain my issue.我的英语不太好,所以很难解释我的问题。 So I put problem in HTML what kind of style I need to get from JS.所以我把问题放在 HTML 我需要从 JS 获得什么样的风格。 Added things.json file as example, and added JS code.添加things.json文件为例,并添加了 JS 代码。

<!-- What I'm getting: -->

<h2>Table</h2>

<ul>
  <li>brown, black, white</li>
</ul>


<!-- What I need to get: -->

<h2>Table</h2>

<ul>
  <li>brown</li>
  <li>black</li>
  <li>white</li>
</ul>

There's example of things.json file:things.json文件的例子:

[
 {
  "thing": "table",
  "color": [
   "brown",
   "black",
   "white"
   ]
  }
  {
  "thing": "chair",
  "color": [
   "yellow",
   "black",
   "blue"
   ]
  }
  {
  "thing": "bed",
  "color": [
   "red",
   "blue",
   "green"
   ]
  }
]

There is example of my function:有我的 function 的例子:

 const ENDPOINT = 'things.json' async function getThing(url) { const resp = await fetch(url) const data = await resp.json() data.forEach(appendToHtml) return data } getThing(ENDPOINT).then((value) => { console.log('getThings', value) }) function appendToHtml(data) { const divEl = document.createElement('div') const h2El = document.createElement('h2') const liEl = document.createElement('li') h2El.textContent = data.thing liEl.textContent = data.color outputEl.append(divEl) divEl.append(h2El) divEl.append(liEl) return divEl }

Assuming your json is an array of objects (with colors) you would need 2 levels of loops.假设您的 json 是一组对象(带颜色),您将需要 2循环。 One for every item (object) in the array.数组中的每个项目(对象)一个。 The other for each object to build the list from its colors (that's also an array).每个 object 的另一个从其 colors (这也是一个数组)构建列表。

 var arr = [{ "thing": "table", "color": [ "brown", "black", "white" ] }, { "thing": "chair", "color": [ "yellow", "black", "blue" ] }, { "thing": "bed", "color": [ "red", "blue", "green" ] }]; var outputEl = document.body; function appendToHtml(data) { const divEl = document.createElement('div') const h2El = document.createElement('h2') const list_container = document.createElement('div') h2El.textContent = data.thing outputEl.append(divEl) divEl.append(h2El) divEl.append(list_container) list_container.innerHTML = appendToList(data.color); return divEl } function appendToList(colors) { return "<ul>" + colors.map(color=>`<li>${color}</li>`).join("\n") + "</ul>" } arr.forEach(function(obj) { appendToHtml(obj) })
 <body> </body>

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

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