实现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); }); }
关键逻辑说明
- 清空目标列表:每次调用函数先清空
targetList的内容,避免多次调用时产生重复列表项,这是部分测试不通过的常见原因。 - 限定操作范围:点击事件中通过
listItem.querySelector查找邮箱元素,确保只操作当前客户对应的列表项,不会影响其他客户的内容。 - 切换逻辑:每次点击姓名时,先检查当前列表项中是否已存在邮箱元素:
- 存在则调用
removeChild移除 - 不存在则创建新的邮箱元素并添加到列表项中
- 存在则调用
常见错误排查
- 如果之前的代码每次点击都直接添加邮箱元素而不判断是否存在,会导致重复添加,无法通过切换隐藏的测试。
- 若使用
document.querySelector而非列表项自身的查询方法,会误操作其他客户的邮箱元素,引发逻辑错误。
内容的提问来源于stack exchange,提问作者reactjs
相关产品推荐
相关产品推荐

