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



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

<textarea id=inline_search></textarea>
<div >
<ul id=show_inline_users>
</ul>
</div>

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("<li class=opt title='"+this.channel+"' >"+this.channel+"</li>");
/*$('.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("<li class=opt title='"+this.channel+"' >"+this.channel+"</li>");
/*$('.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,则会出现一个用户建议列表

<ul id=show_inline_users>
<li class=opt title='Jenna'>Jenna</li>
<li class=opt title='Jeremy'>Jeremy</li>
<li class=opt title='Jean'>Jean</li>
<li class=opt title='Jelly'>Jelly</li>
</ul>

如果我单击Jean Option,标题值将替换文本区域中的用户文本,例如在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;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<textarea id="post">
Im gonna tag @Je
</textarea>
<ul id=show_inline_users>
<li class=opt title='Jenna'>Jenna</li>
<li class=opt title='Jeremy'>Jeremy</li>
<li class=opt title='Jean'>Jean</li>
<li class=opt title='Jelly'>Jelly</li>
</ul>

最新更新