让jQuery用户界面自动完成与@mentions工作只 [英] getting jQuery ui autocomplete to work with @mentions only

查看:125
本文介绍了让jQuery用户界面自动完成与@mentions工作只的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我看了一下几个问题,如 http://stackoverflow.com/a/7222592/2332251

I've had a look at a few questions, such as http://stackoverflow.com/a/7222592/2332251

我仍然有麻烦了code我有协调的。

I'm still having trouble reconciling it with the code I have.

目前完全用于搜索用户名,因为我开始打字了以下工作。

At the moment the following works perfectly for searching a username as I start typing.

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

在searchusers.php功能从数据库中输出的用户名。

The function in searchusers.php outputs the usernames from the database.

正如我所说的,我无法作出其他@mention解决方案,为我工作。我试图复制比其他解决方案,并在交换我的细节,但似乎没有任何工作。

As I said, I'm having trouble making other @mention solutions work for me. I've tried copying over other solutions and swapping my details in but nothing seems to work.

所以...


  1. 什么我需要做的,我目前的自动完成脚本,使它只加载
    当我最初键入@符号?

  2. 我真的很希望能有多个@mentions在我的职位

  3. (可选)时自动完成建议用户名,当我从列表中选择用户名,我希望它出现在我的岗位与仍然附加到用户名前面例如@symbol 你好@约翰,@符号仍连接到您的用户名

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

If you need more info, please comment and I will provide more :)

修改我真的非常不确定的语法,使其工作。例如,在使用的例子回答我上面贴出来,我想出了(但它不工作):

Edit I'm just really unsure of the syntax to make it work. For example, using the example answer I posted above, I came up with (but it doesn't work):

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等具体信息?我希望这是有道理的。

Where do I insert searchusers.php, #appendedInputButton and other specific info? I hope this makes sense.

推荐答案

我会根据我的意见形成了答案。

I will form an answer based on my comments.

首先让审查的要求清单:

First of all lets review the list of requirements:


  • 自动完成用户名开始与 @ 符号

  • prePEND用户名与 @ 符号

  • 在文本多@mentions

  • 编辑文本的任何地方任何@mention

实施最后一个要求,我们需要一些神奇的功能,我就发现了计算器:

to implement the last requirement we need some magic functions that i found on stackoverflow:

  • getCaretPosition - http://stackoverflow.com/a/2897229/2335291
  • setCaretPosition - http://stackoverflow.com/a/512542/2335291

另外要在我们需要定义用户名一些限制文本某处发现一个用户名。我认为它只能有字母和数字,并与 \\测试W + 模式。

Also to detect a username somewhere in the text we need to define some constraints for usernames. I assume that it can have only letters and numbers and test it with \w+ pattern.

的现场演示,你可以在这里找到 http://jsfiddle.net/AU92X/6/ 它总是返回2行不进行过滤只是为了演示的行为。在列表下方的我已经把原来的 getTags 从功能,因为它看起来对我罚款的问题。虽然我不知道如何 searchusers.php

The live demo you can find here http://jsfiddle.net/AU92X/6/ It always returns 2 rows without filtering just to demonstrate the behavior. In the listing below i've put the original getTags function from the question as it looks fine for me. Although i have no idea how searchusers.php works.

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);
    };
});

这篇关于让jQuery用户界面自动完成与@mentions工作只的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆