jquery autocomplete @mention

时间:2012-04-08 05:06:31

标签: javascript jquery jquery-ui jquery-plugins javascript-events

嘿伙计们我有来自Andrew Whitaker的这个自动完成插件 - DEMO 让我说我在 textarea中有一个字符串

  

“@ peterwateber welcome”

我希望它以隐藏标签输出

  

“@ [peterwateber] welcome”

我应该怎么做?我对javascript并不擅长......

我已尝试从Hawkee查看此代码 here

2 个答案:

答案 0 :(得分:4)

Hiya 工作演示http://jsfiddle.net/67dxH/

上面已经进行了很好的讨论,就像你说的那样行为就像:value of the hidden tag as = @[C#] and the textarea as @C#

Jope这是有帮助的人,让我知道它是怎么回事,干杯! :)

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() {

    $("#tags")
    // 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
            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 $("<li>")
            .data("item.autocomplete", item)
            .append("<a>@[" + item.label + "]&nbsp;<span class='count'>(" + item.count + ")</span></a>")
            .appendTo(ul);
    };
});​

答案 1 :(得分:1)

我写了这里提到的原始代码并修复了Peter所遇到的菜单问题:

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