将jQuery Text Complete与包含Key和Value的数组一起使用

时间:2015-06-28 22:55:12

标签: javascript jquery arrays

我使用jQuery.textcomplete插件使用以下代码:

$('#textarea3').textcomplete([
    { // html
        mentions: {
            'test': 'test@gmail.com', 
            'othertest': 'othertest@gmail.com'
        },
        match: /\B@(\w*)$/,
        search: function (term, callback) {
            callback($.map(this.mentions, function (mention) {
                return mention.indexOf(term) === 0 ? mention : null;
            }));
        },
        index: 1,
        replace: function (mention) {
            return '@' + mention + ' ';
        }
    }
]);

我希望当用户输入 @te 时显示选项,但只显示mention.[value]而我不想返回replace: function喜欢

replace: function (mention) {
    return '@' + mention.[key] + ' ';
}

那么,我该怎么办?

3 个答案:

答案 0 :(得分:2)

将提及dict转换为数组,然后就可以了。

var mentions = {
  'test': 'test@gmail.com', 
  'othertest': 'othertest@gmail.com'
};

var arrayOfMentions = Object.keys(mentions).map(function(key) {
  var val = {};
  val[key] = mentions[key];
  return val;
});

$('textarea').textcomplete([
  {
    mentions: arrayOfMentions,
    match: /\B@(\w*)$/,
    search: function (term, callback) {
      callback($.map(this.mentions, function (mention) {
        var value = mention[Object.keys(mention)[0]];
        return value.indexOf(term) === 0 ? mention : null;
      }));
    },
    template: function (mention) {
      return mention[Object.keys(mention)[0]];
    },
    index: 1,
    replace: function (mention) {
      var key = Object.keys(mention)[0];
      return '@' + key + ' ';
    }
  }
]);

请参阅http://jsbin.com/farewa/edit?js,output

处的jsbin

答案 1 :(得分:1)

像这样......我正在努力做个小提琴......

        callback($.map(this.mentions, function (mention) {
            for (property in this.mentions) {
                  return mention.indexOf(property) === 0 ? mention : null;
            }

        }));

答案 2 :(得分:0)

我的情况不是一个:我需要在keys中搜索,但用value代替:

$('#maintext').textcomplete([{
  mentions: arrayOfMentions,
  match: /\B@(\w*)$/,
  search: function(term, callback) {
    callback($.map(this.mentions, function(mention) {
      var key = Object.keys(mention)[0];
      return key.indexOf(term) === 0 ? mention : null;
    }));
  },
  template: function(mention) {
    return '@' + Object.keys(mention)[0];
  },
  index: 1,
  replace: function(mention) {
    var key = Object.keys(mention)[0];
    if(mention[key]){
        return mention[key];
    } else {
        return '@' + key + ' ';
    }
  }
}]);

见这里:https://jsfiddle.net/FabioBeneditto/od5jumvh/