我正在使用Andrew Whitaker的autocomplete插件,在这个问题中也引用了: jquery autocomplete @mention
如果我使用contenteditable div而不是textarea,这不起作用。这是我的代码:
<div id="MyText" contenteditable="true"></div>
$("#MyText").bind("keydown", function (event) {
if (event.keyCode === $.ui.keyCode.TAB && $(this).data("autocomplete").menu.active) {
event.preventDefault();
}
}).autocomplete({
minLength: 0,
source: function (request, response) {
var term = request.term,
results = [];
if (term.indexOf("@") >= 0) {
term = extractLast(request.term);
if (term.length > 0) {
results = $.ui.autocomplete.filter(tags, term);
} else {
results = [startTyping];
}
}
response(results);
},
focus: function () {
return false;
},
select: function (event, ui) {
if (ui.item.value !== startTyping) {
var terms = this.value.split(' ');
terms.pop();
terms.push("@" + ui.item.value + "</span>");
this.value = terms.join(" ");
}
return false;
}
}).data("autocomplete")._renderItem = function (ul, item) {
if (item.label != startTyping) {
return $("<li></li>")
.data("item.autocomplete", item)
.append("<a><div><img src='" + item.icon + "'/></div><div>" + item.label + "</div></div></a>")
.appendTo(ul);
} else {
return $("<li></li>")
.data("item.autocomplete", item)
.append("<a>" + item.label + "</a>")
.appendTo(ul);
}
};
有什么想法吗?
答案 0 :(得分:16)
输入/ textarea和contenteditable div之间的主要区别在于您使用.html()方法(而不是.value或.val()方法访问后者内容。
以下是自动填充代码:
$("#MyText")
.bind("keydown", function (event) {
if (event.keyCode === $.ui.keyCode.TAB && $(this).data("autocomplete").menu.active) {
event.preventDefault();
}
})
.autocomplete({
minLength: 0,
source: function (request, response) {
var term = request.term,
results = [];
if (term.indexOf("@") >= 0) {
term = extractLast(request.term);
if (term.length > 0) {
results = $.ui.autocomplete.filter(tags, term);
} else {
results = [startTyping];
}
}
response(results);
},
focus: function () {
return false;
},
select: function (event, ui) {
if (ui.item.value !== startTyping) {
var value = $(this).html();
var terms = split(value);
terms.pop();
terms.push(ui.item.value);
$(this).html(terms.join("@"));
placeCaretAtEnd(this);
}
return false;
}
})
.data("autocomplete")._renderItem = function (ul, item) {
if (item.label != startTyping) {
return $("<li></li>")
.data("item.autocomplete", item)
.append("<a><div>" + item.label + "</div></div></a>")
.appendTo(ul);
} else {
return $("<li></li>")
.data("item.autocomplete", item)
.append("<a>" + item.label + "</a>")
.appendTo(ul);
}
}
;
编辑(2):这是link to the jsfiddle
答案 1 :(得分:2)
以上示例不起作用请参阅此http://jsfiddle.net/ipsjolly/jYJjJ/29/
select: function (event, ui) {
var value = $(this).html();
var terms = split(value);
terms.pop();
terms.push(ui.item.value);
$(this).html(terms+", ");
placeCaretAtEnd(this);
return false;
}