You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

实现showCustomers函数:点击姓名切换邮箱元素的显示状态

解决TestDome showCustomers函数的邮箱切换问题

以下是完整的实现代码,可满足所有测试要求:

function showCustomers(customers, targetList) {
  // 清空目标列表,避免重复渲染
  targetList.innerHTML = '';

  customers.forEach(customer => {
    const listItem = document.createElement('li');
    
    // 创建姓名元素
    const namePara = document.createElement('p');
    namePara.textContent = customer.name;
    namePara.classList.add('customer-name');

    // 绑定点击切换逻辑
    namePara.addEventListener('click', () => {
      const emailPara = listItem.querySelector('.customer-email');
      
      if (emailPara) {
        // 已存在则移除邮箱元素
        listItem.removeChild(emailPara);
      } else {
        // 不存在则创建并添加邮箱元素
        const newEmailPara = document.createElement('p');
        newEmailPara.textContent = customer.email;
        newEmailPara.classList.add('customer-email');
        listItem.appendChild(newEmailPara);
      }
    });

    listItem.appendChild(namePara);
    targetList.appendChild(listItem);
  });
}

关键逻辑说明

  1. 清空目标列表:每次调用函数先清空targetList的内容,避免多次调用时产生重复列表项,这是部分测试不通过的常见原因。
  2. 限定操作范围:点击事件中通过listItem.querySelector查找邮箱元素,确保只操作当前客户对应的列表项,不会影响其他客户的内容。
  3. 切换逻辑:每次点击姓名时,先检查当前列表项中是否已存在邮箱元素:
    • 存在则调用removeChild移除
    • 不存在则创建新的邮箱元素并添加到列表项中

常见错误排查

  • 如果之前的代码每次点击都直接添加邮箱元素而不判断是否存在,会导致重复添加,无法通过切换隐藏的测试。
  • 若使用document.querySelector而非列表项自身的查询方法,会误操作其他客户的邮箱元素,引发逻辑错误。

内容的提问来源于stack exchange,提问作者reactjs

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.22 12:36:24