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

页面时间线评论@用户标签重复叠加问题求助(附代码)

解决@用户时用户名重复叠加的问题

问题场景:实现评论@功能时,输入@触发用户选择列表,选中用户后出现用户名重复叠加(如@namenamename),期望效果是选中用户后替换以@开头的目标词汇。

问题原因

原代码逻辑是直接将选中的用户名追加到输入框现有内容末尾,没有处理已经输入的@及后续字符,导致多次选择时重复叠加。

修改后的代码

$(document).ready(function(){
    $('#notes-input').bind('keypress', function(e) {
        if(e.keyCode === 64){
            $('#userlist').removeClass('d-none');
        }
    });

    $(document).on('click','#userlist', function(e){                                                             
        const username = $(this).find('option:selected').val();
        const $input = $('#notes-input');
        let inputVal = $input.val();
        // 找到最后一个@的位置
        const atIndex = inputVal.lastIndexOf('@');
        
        if (atIndex !== -1) {
            // 替换从@开始到末尾的内容为@+用户名
            inputVal = inputVal.substring(0, atIndex) + `@${username}`;
        } else {
            // 特殊情况:无@时直接添加
            inputVal += `@${username}`;
        }
        
        $input.val(inputVal);
        $('#userlist').addClass('d-none');
        $input.focus();
    }); 
});

关键修改说明

  • 定位输入框内容中**最后一个@**的位置,确保只替换最近一次触发@的目标内容
  • 将从@开始到末尾的内容替换为@${username},实现“替换以@开头的词汇”的需求
  • 使用const声明变量,提升代码规范性

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.26 17:50:11