单击列表jquery上的结果后自动完成textarea文本

我正在为用户创建一个textarea来创建post。 在这些post中,他们有可能标记某人@myfriend 。 我成功地使用了@NiMusco帮助,开发了jquery代码,但是在点击其中一个结果后,我在自动填充时遇到了麻烦,例如将@Jean (列出的结果)替换为textarea中写的@Je

   

php输出json数据,这种类型

 $arr[] = array("channel" => $obj->channel,...); /* Return JSON */ echo json_encode($arr); 

Jquery是正确的,但我不能自动完成用户名

 var count = 0; var tagging = false; $('#inline_search').keyup(function(){ var text = $(this).val(); if(text.length > count){ var lastChar = text.substr(count); if(lastChar == "@"){ tagging = true; } //White space break the tagging. if(lastChar == " "){ tagging = false; } //Adapt this to your tagging function if(tagging == true){ var username = text.substr(text.lastIndexOf('@') + 1, text.length); ////////////INLINE SEARCH INI/////////////////////////////////////// var searchKeyword = username; if(searchKeyword.length>0){ $.post('search/users.php', { keywords: searchKeyword }, function(data) { $('#show_inline_users').empty(); $.each(data, function() { $('#show_inline_users').append("
  • "+this.channel+"
  • "); /*$('.opt').click(function(){ var user_title = $(this).attr("title"); alert(user_title); $('#inline_search').val($('#inline_search').val()+ " @"+user_title); });*/ }); },"json").fail(function(xhr, ajaxOptions, thrownError) { //any errors? alert(thrownError); //alert with HTTP error }); }else{$('#show_inline_users').empty();} ///////////////INLINE SEARCH END////////////////////////////////////// } } count = text.length; });

    我在这些行上有问题,我想用.attr()来替换

      $('#show_inline_users').append("
  • "+this.channel+"
  • "); /*$('.opt').click(function(){ var user_title = $(this).attr("title"); alert(user_title); $('#inline_search').val($('#inline_search').val()+ " @"+user_title); });*/ });*/

    例如,如果我输入Hi my username on stackoverflow is @Je textarea中的Hi my username on stackoverflow is @Je出现一个用户建议列表

      
    • Jenna
    • Jeremy
    • Jean
    • Jelly

    如果我单击Jean选项,标题值将替换textarea中的用户文本,如twitter或faceb0ok。

    好吧,抱歉延误了。 请记住,标签菜单仅出现在@之后。 我们在这里有“@”的最后一个位置:text.lastIndexOf(’@’)。

    像这样的东西(但适应你所拥有的)。 尝试点击不同的名称。

     var text = $('#post').val(); var at_pos = text.lastIndexOf('@'); $('.opt').click(function(){ var username = $(this).attr("title"); text = text.substring(0, at_pos); text = text + username; $('#post').val(text); }); 
     #post{ width:300px; height:50px; } 
       
    • Jenna
    • Jeremy
    • Jean
    • Jelly