1

我看过一些问题,例如https://stackoverflow.com/a/7222592/2332251

我仍然无法将其与我拥有的代码进行协调。

目前,以下内容非常适合在我开始输入时搜索用户名。

$(function() {
    $("#appendedInputButton").autocomplete({
        minLength: 2,  
    source: "searchusers.php" 
        });                
});

searchusers.php 中的函数从数据库中输出用户名。

正如我所说,我无法让其他 @mention 解决方案为我工作。我尝试过复制其他解决方案并交换我的详细信息,但似乎没有任何效果。

所以...

  1. 我需要对当前的自动完成脚本执行什么操作才能使其仅在我最初键入“@”符号时才加载?
  2. 我真的希望能够在我的帖子中有多个@mentions
  3. (可选)当自动完成建议用户名并且当我从列表中选择用户名时,我希望它出现在我的帖子中,@symbol 仍附加到用户名的前面,例如“你好 @john,@ 符号仍附加到您的用户名”

如果您需要更多信息,请发表评论,我会提供更多信息:)

编辑我真的不确定使它起作用的语法。例如,使用我上面发布的示例答案,我想出了(但它不起作用):

function split(val) {
return val.split(/@\s*/);
}

function extractLast(term) {
    return split(term).pop();
}

function getTags(term, callback) {
    $.ajax({
        url: "searchusers.php",
        data: {
            filter: term,
            pagesize: 5
        },
        type: "POST",
        success: callback,
        jsonp: "jsonp",
        dataType: "jsonp"
    });    
}

$(document).ready(function() {

$("#appendedInputButton")
// 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
        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);
};
});

我在哪里插入 searchusers.php、#appendedInputButton 和其他特定信息?我希望这是有道理的。

4

2 回答 2

4

我将根据我的评论形成答案。

首先让我们回顾一下需求列表:

  • @以符号开头的自动完成用户名
  • 在用户名前面加上@符号
  • 文本中的多个@提及
  • 在文本中的任何位置编辑任何@提及

为了实现最后一个要求,我们需要一些我在 stackoverflow 上找到的魔法函数:

此外,为了检测文本中某处的用户名,我们需要为用户名定义一些约束。我假设它只能有字母和数字并用\w+模式测试它。

您可以在此处找到现场演示http://jsfiddle.net/AU92X/6/它总是返回 2 行而不进行过滤,只是为了演示行为。在下面的清单中,我已将getTags问题中的原始函数放入其中,因为它对我来说看起来不错。虽然我不知道如何searchusers.php工作。

function getCaretPosition (elem) {

  // Initialize
  var iCaretPos = 0;

  // IE Support
  if (document.selection) {

    // Set focus on the element
    elem.focus ();

    // To get cursor position, get empty selection range
    var oSel = document.selection.createRange ();

    // Move selection start to 0 position
    oSel.moveStart ('character', -elem.value.length);

    // The caret position is selection length
    iCaretPos = oSel.text.length;
  }
  // Firefox support
  else if (elem.selectionStart || elem.selectionStart == '0')
    iCaretPos = elem.selectionStart;

  // Return results
  return (iCaretPos);
}

function setCaretPosition(elem, caretPos) {
    if(elem != null) {
        if(elem.createTextRange) {
            var range = elem.createTextRange();
            range.move('character', caretPos);
            range.select();
        }
        else {
            if(elem.selectionStart) {
                elem.focus();
                elem.setSelectionRange(caretPos, caretPos);
            }
            else
                elem.focus();
        }
    }
}

function getTags(term, callback) {
    $.ajax({
        url: "searchusers.php",
        data: {
            filter: term,
            pagesize: 5
        },
        type: "POST",
        success: callback,
        jsonp: "jsonp",
        dataType: "jsonp"
   });    
}

$(document).ready(function() {
    $("#appendedInputButton").autocomplete({
        source: function(request, response) {
            var term = request.term;
            var pos = getCaretPosition(this.element.get(0));
            var substr = term.substring(0, pos);
            var lastIndex = substr.lastIndexOf('@');
            if (lastIndex >= 0){
                var username = substr.substr(lastIndex + 1);
                if (username.length && (/^\w+$/g).test(username)){
                    getTags(username, function(data) {
                        response($.map(data.tags, function(el) {
                            return {
                                value: el.name,
                                count: el.count
                            }
                        }));
                    });
                    return;
                }
            }

            response({}); 
        },
        focus: function() {
            // prevent value inserted on focus
            return false;
        },
        select: function(event, ui) {
            var pos = getCaretPosition(this);
            var substr = this.value.substring(0, pos);
            var lastIndex = substr.lastIndexOf('@');
            if (lastIndex >= 0){
                var prependStr = this.value.substring(0, lastIndex);
                this.value = prependStr + '@' + ui.item.value + this.value.substr(pos);
                setCaretPosition(this, prependStr.length + ui.item.value.length + 1);
            }    
            return false;
        }
    }).data("ui-autocomplete")._renderItem = function(ul, item) {
        return $("<li>")
            .data("ui-autocomplete-item", item)
            .append("<a>" + item.label + "&nbsp;<span class='count'>(" + item.count + ")</span></a>")
            .appendTo(ul);
    };
});
于 2013-06-11T16:06:41.183 回答
0

I cannot add a comment, so I'm just going to add this as an answer.

I tried the code snippet you've provided and it worked great. The only problem I had was while editing the mention. I decided to edit from the middle of the mention, the autocomplete showed and I selected an item successfully. Only - it didn't delete the rest of the previous mention, only the letters before the cursor's position.

So I added something extra:

select: function(event, ui) {
    var pos = comments.init.getCaretPosition(this);
    var substr = this.value.substring(0, pos);
    var lastIndex = substr.lastIndexOf('@');

    var afterPosString = this.value.substring(pos, this.value.length);
    var leftovers = afterPosString.indexOf(' ');
    if (leftovers == -1)
        leftovers = afterPosString.length;

    if (lastIndex >= 0){
        var prependStr = this.value.substring(0, lastIndex);
        this.value = prependStr + '@' + ui.item.value + this.value.substr(pos + leftovers);
        comments.init.setCaretPosition(this, prependStr.length + ui.item.value.length + 1);
    }    
    return false;
}

I changed the select function a bit to cover the leftovers. Now, it's searching for the next " " occurrence and adds the length of everything before it to the replaced value.

Hope this helps :)

于 2016-06-23T16:18:00.577 回答