我想在我的rails应用程序中创建一个@ other people函数,就像stackoverflow一样:
我差不多完成了这个功能,但是我遇到了问题,jQuery auto-compelete数据替换了我的textarea内容,而不是追加.
CoffeeScript的:
find_at_sign = ->
if $("#tags").val().split('').pop() == "@"
id = $("#tags").data("article-id")
$("#tags").autocomplete
source: '/articles/' + id + '/autocomplete.json'
minLength: 1
$->
$(document).on("input", "#tags",
-> find_at_sign())
文章管理员:
def autocomplete
@articles = Article.find_by(id: params[:article_id])
@commentor_names = @articles.comments.map(&:name).uniq
respond_to do |format|
format.html
format.json {
render json: @commentor_names
}
end
end
form_html.erb:
<div class="form-group ui-widget">
<div class="col-sm-5">
<%= f.text_area :content, rows: 5, placeholder: '说点什么...',
class: 'form-control', id: "tags", 'data-article-id': @article.id.to_s %>
</div>
</div>
我试图使用append方法,但不起作用:
$("#tags").append(${this).autocomplete
source: '/articles/' + id + '/autocomplete.json'
minLength: 1)
任何帮助都很感激!
最佳答案 基于
this example,这是我对此的半心半意的尝试.重点是如下:
>取消内置的focus
事件,该事件试图覆盖文本框内的值
>取消内置的select
事件并将其配置为将选定的@name附加到文本框中而不是覆盖它
>提供自定义source
函数,该函数从文本框中提取最后一个@name并查找该名称并返回匹配的名称
var namelist = [
"Adam",
"Adrian",
"Andrew",
"Charles",
"Daniel",
"David",
"Evan",
"Henry",
"Ian",
"Jack",
"James",
"John",
"Joseph",
"Justin",
"Kevin",
"Michael",
"Parker",
"Robert",
"Thomas",
"William"
];
$(function() {
$("#message").autocomplete({
source: function(request, response) {
var match = request.term.match(/@(\w*)$/);
var names = match ? $.ui.autocomplete.filter(namelist, match[1]) : [];
response(names)
},
focus: function(event) {
event.preventDefault();
},
select: function(event, ui) {
event.preventDefault();
this.value = this.value.replace(/@(\w*)$/, "@" + ui.item.value)
}
})
});
@import url("https://code.jquery.com/ui/1.11.4/themes/ui-darkness/jquery-ui.min.css");
body {
font: smaller sans-serif;
}
textarea {
box-sizing: border-box;
width: 100%;
height: 5em;
}
<script src="https://code.jquery.com/jquery-1.12.4.min.js"></script>
<script src="https://code.jquery.com/ui/1.11.4/jquery-ui.min.js"></script>
<p>Enter some text or @name</p>
<textarea id="message"></textarea>