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

求助:JavaScript实现表格手机号重复输入拦截失败问题

手机号重复录入问题解决

你的代码核心问题在于同一个linhas数组混合存储了手机号字符串和HTML行字符串,导致linhas.includes(inputNumeroTelefone.value)判断完全失效——第一次添加联系人时,先把手机号推入数组,接着又把HTML行字符串推入数组,后续检查重复时,数组里大部分元素是HTML字符串,自然匹配不到手机号,所以重复录入无法被拦截。

修正后的代码

const form = document.getElementById('agenda-de-contatos');
// 单独用数组存储联系人数据,每个元素是包含姓名和手机号的对象
const contatos = [];

form.addEventListener('submit', function (e) {
    e.preventDefault();
    const inputNomeContato = document.getElementById('nome-do-contato');
    const inputNumeroTelefone = document.getElementById('numero-de-telefone');
    const telefone = inputNumeroTelefone.value.trim();
    const nome = inputNomeContato.value.trim();

    // 检查是否已存在相同手机号的联系人
    const existeContato = contatos.some(item => item.telefone === telefone);
    if (existeContato) {
        alert(`Número: ${telefone} já foi inserido`);
        inputNumeroTelefone.value = '';
        inputNumeroTelefone.focus();
        return;
    }

    // 添加新联系人到数据数组
    contatos.push({ nome, telefone });
    // 重新渲染表格
    renderizarTabela();

    // 清空输入框并聚焦
    inputNomeContato.value = '';
    inputNumeroTelefone.value = '';
    inputNomeContato.focus();
})

function renderizarTabela() {
    const corpoTabela = document.querySelector('tbody');
    // 遍历数据数组生成HTML行
    const linhasHTML = contatos.map((contato, index) => `
        <tr>
            <td>${contato.nome}</td>
            <td>${contato.telefone}</td>
            <td><button class='excluir' onclick="deleteRow(${index})">Remover</button></td>
        </tr>
    `);
    corpoTabela.innerHTML = linhasHTML.join('');
}

function deleteRow(index) {
    // 删除数据数组中对应索引的联系人
    contatos.splice(index, 1);
    // 重新渲染表格
    renderizarTabela();
}

关键修改点

  • 拆分数据与视图:用contatos数组专门存储联系人数据(对象格式),彻底避免数据和HTML结构混淆
  • 准确检测重复:用Array.some()遍历数据数组,直接匹配手机号字段,判断逻辑精准
  • 统一渲染逻辑:单独封装renderizarTabela函数,添加或删除联系人时重新渲染表格,避免手动拼接HTML的混乱
  • 简化删除逻辑:通过数据数组的索引删除对应项,再重新渲染,无需操作DOM行索引,减少出错概率

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.13 08:40:27