0

我正在尝试从 TestDome 解决这个挑战,我需要一些帮助。我真的不明白我必须如何切换电子邮件以及如何将项目附加到 DOM... !!请不要只使用 Vanilla JS !

实现 showCustomers 函数,以便将客户呈现为列表项。函数的第一个参数customers 是一个包含name 和email 属性的对象数组。该函数的第二个参数 targetList 是一个无序的 HTML 列表,每个客户都应作为单独的列表项添加到该列表中。

名称和电子邮件属性应作为两个段落添加到列表项中。首先,电子邮件段落元素不应该出现在 DOM 中。电子邮件段落元素应在单击名称后添加到 DOM 中,并应在再次单击名称时从 DOM 中删除。

例如,下面的代码:

document.body.innerHTML = `
<div>
  <ul id="customers">
  </ul>
</div>
`;
let customers = [{name: "John", email: "john@example.com"},
                 {name: "Mary", email: "mary@example.com"}];
showCustomers(customers, document.getElementById("customers"));

let customerParagraph = document.querySelectorAll("li > p")[0];
if(customerParagraph) {
  customerParagraph.click();
}
console.log(document.body.innerHTML);
Should render:

<div>
  <ul id="customers">
    <li>
      <p>John</p>
      <p>john@example.com</p>
    </li>
    <li>
      <p>Mary</p>
    </li>
  </ul>
</div>

这是我的代码

function showCustomers(customers, targetList) {
 customers.forEach(item =>{
  let res = `<li>
        <p> ${item.name}</p>;
        <p> ${item.email}</p>;
        </li>;
  targetList.innerHTML = targetList.appendChild(res);
   
 })
}

https://www.testdome.com/questions/javascript/customer-list/49798?visibility=3&skillId=2

4

1 回答 1

0

换行

targetList.innerHTML = targetList.appendChild(res);

targetList.innerHTML += res;.

您基本上有两种添加元素的方法:

  • 使用原始字符串增加 innerHTML 内容
  • 将子元素附加到 DOM 元素

在你的情况下res是一个字符串,所以你不能使用targetList.appendChild

于 2022-01-19T17:12:59.227 回答