简体   繁体   English

如何从该异步等待 function 中成功从数据库中获取数据的 output 样式?

[英]How do I style the output from this async await function that successfully fetches data from a database?

<script>
        getData();

        async function getData() {
          const response = await fetch("/members");
          const data = await response.json();

          for (item of data) {
            const root = document.createElement("div");
            const member = document.createElement("div");
            member.textContent = `member: ${item.member}`;

            root.append(
              item.firstname,
              item.lastname,
              item.mobile,
              item.contactname,
              item.contactphone
            );
            document.body.append(root);
          }
          console.log(data);
        }
</script>

The same way you style anything else.就像你设计其他任何东西一样。 Write a CSS rule.编写 CSS 规则。 Add whatever classes (eg member.classList.add("foo") ), etc. you need to design a specific enough selector to the element.添加任何需要为元素设计足够具体的选择器的类(例如member.classList.add("foo") )等。

Just add a class to it with member.classList.add('member-item')只需使用member.classList.add('member-item')向其中添加 class

example例子

<head>
<style> 
.member-item {
background-color: white;
} 
</style>
</head>
<body>
<div id="root" />
<script>
       const root = document.querySelector('#root')

async function getData() {
  // const response = await fetch("/members");
  // const data = await response.json();
  const sampleData = [{
    firstName: 'Dave',
    lastname: 'Smith',
    mobile: '0632452345',
    contactname: 'Dave',
    contactphone: '0632452345',
  },
                     {
    firstName: 'Mike',
    lastname: 'Smith',
    mobile: '06324234345',
    contactname: 'Mike',
    contactphone: '0635435345',
  }]

for(let i = 0; i < sampleData.length; i+= 1) {
  const div = document.createElement('div');
  div.innerHTML = `
<p>First Name ${sampleData[i].firstName}</p>
<p>Last Name ${sampleData[i].lastname}</p>
<p>mobile Name ${sampleData[i].mobile}</p>
<p>Contact Name ${sampleData[i].contactname}</p>
<p>Contact Phone ${sampleData[i].contactphone}</p>
<hr>
`;
  root.append(div)
}
}

getData()
</script>
</body>



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

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