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

使用JS和AJAX开发姓名搜索栏功能失效,如何修改对应JS代码

搜索功能失效核心问题
  • 你当前的nameFilter函数第一行就执行了$("#memberList").html("")清空了所有成员DOM,后续筛选时已经没有可查询的元素,自然无法展示匹配结果
  • 没有处理搜索关键词为空时恢复全部成员的逻辑
  • 直接把用户输入拼接进jQuery选择器存在XSS注入风险,且:contains默认大小写敏感,匹配体验不好
修正后的搜索功能代码

直接替换你原有的nameFilter函数即可:

function nameFilter() {
    const searchVal = $('#searchName').val().trim();
    // 遍历所有成员项做匹配
    $('#memberList .family').each(function() {
        const currentName = $(this).find('.member-name').text();
        // 大小写不敏感匹配,不需要可去掉.toLowerCase()
        const matchRes = currentName.toLowerCase().includes(searchVal.toLowerCase());
        $(this).toggle(matchRes);
    });
}
可选优化项(非必须)

你原有生成成员列表的代码重复逻辑较多,可以简化为以下写法,减少冗余:

// 先把公共配置抽出来
const today = common_getTodayWithHyphen();
const hideDeleteBtn = '<div class="button-area"><button type="button" class="button-member-hide">hide</button><button type="button" class="button-member-delete">delete</button></div>';

for (let i in user.family) {
    const item = user.family[i];
    const { familyUserSn, familyMemberNm, userProflPhotoCn, memberCreatDt } = item;
    // 处理头像
    const avatarBase64 = userProflPhotoCn && userProflPhotoCn >=1 ? userProflPhotoCn : DATA_NO_PROFILE;
    // 处理New标识
    const newLabel = memberCreatDt === today ? '<label class="new">N</label>' : '';
    // 拼接DOM
    const family = `
    <li class="family" id="${familyUserSn}">
        <div class="member-profile">
            <figure class="default-bg">
                <img src="data:image/jpeg;base64,${avatarBase64}" alt="profilePicture">
            </figure>
            ${newLabel}
        </div>
        <p class="member-name">${familyMemberNm}</p>
        ${hideDeleteBtn}
    </li>`;
    $("#memberList").append(family);
}
// 自动选中第一个成员
$(".family").first().click();

注意:原有删除按钮用了固定idmemberDeletePopUp,循环生成会导致id重复,已经在上面的优化代码中移除,建议用class绑定点击事件。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.27 08:54:03