使用’@’进行jquery自动完成

我想使用jQuery UI Autocomplete来实现这种输出 (fiddler demo)。

我的示例唯一的问题是箭头键事件中存在问题,而不像jquery自动完成。

我写了这个问题中提到的小部件,并修复了问题:

http://www.hawkee.com/snippet/9391/

这里的工作演示: http : //jsfiddle.net/cH4p4/&& http://jsfiddle.net/LxpQQ/

就像你提到的使用自动完成一样:

“所以我的textarea输出将是”@ c#“,输入标签输出将是”@ [c#]“

HTML

 

Jquery代码

 function split(val) { return val.split(/@\s*/); } function extractLast(term) { return split(term).pop(); } function getTags(term, callback) { $.ajax({ url: "http://api.stackoverflow.com/1.1/tags", data: { filter: term, pagesize: 5 }, type: "POST", success: callback, jsonp: "jsonp", dataType: "jsonp" }); } $(document).ready(function() { $("#inputbox") // don't navigate away from the field on tab when selecting an item .bind("keydown", function(event) { if (event.keyCode === $.ui.keyCode.TAB && $(this).data("autocomplete").menu.active) { event.preventDefault(); } }).autocomplete({ source: function(request, response) { if (request.term.indexOf("@") >= 0) { $("#loading").show(); getTags(extractLast(request.term), function(data) { response($.map(data.tags, function(el) { return { value: el.name, count: el.count } })); $("#loading").hide(); }); } }, focus: function() { // prevent value inserted on focus return false; }, select: function(event, ui) { var terms = split(this.value); // remove the current input terms.pop(); // add the selected item $("#tags").val("@["+ui.item.value+"]"); ui.item.value = "@" + ui.item.value; terms.push(ui.item.value); // add placeholder to get the comma-and-space at the end terms.push(""); this.value = terms.join(""); return false; } }).data("autocomplete")._renderItem = function(ul, item) { return $("
  • ") .data("item.autocomplete", item) .append("@[" + item.label + "] (" + item.count + ")") .appendTo(ul); }; });​
  • CSS

     span.count { font-style: italic; color: #C0C0C0; } .hidden { display: none; } textarea { width: 300px; height: 100px; resize: none; }​ 

    您可以尝试以下我们刚刚在GitHub中开源的jquery插件: https : //github.com/tactivos/jquery-sew