多对象数组在At.js中不起作用

时间:2018-10-07 10:43:47

标签: javascript jquery at.js

我正在使用At.js plugin。单个对象(demo)正常工作

var names1 = ["Jacob", "Isabella", "Ethan", "Emma", "Daniel", "Madison"];
var names = $.map(names1, function(value, i) {
  return {
    'id': i,
    'name': value,
    'email': value + '@yahoo.com'
  };
});

但是当我尝试添加多个对象时,它不起作用(demo)。我知道代码是问题所在。 我想在用户使用@标签选择人名时显示说明。

$(function() {
  $.fn.atwho.debug = true

  var names1 = [{
      "name": "Jacob",
      "description": "description one description one description one"
    },
    {
      "name": "Isabella",
      "description": "description two description two description two"
    }
  ];

  var names = $.map(names1, function(value, description, i) {
    return {
      'id': i,
      'name': value,
      'email': description
    };
  });

  var at_config = {
    at: "@",
    data: names,
    headerTpl: '<div class="atwho-header">Service List <small>↑&nbsp;↓&nbsp;</small></div>',
    insertTpl: '${email}',
    displayTpl: "<li>${name}</li>",
    limit: 200
  }
  $inputor = $('#inputor').atwho(at_config);
  $inputor.caret('pos', 47);
  $inputor.focus().atwho('run');
});

1 个答案:

答案 0 :(得分:1)

Jquery中的map函数没有将对象中的每个元素都用作函数参数,而是获取了整个对象(列表中的元素),然后需要提取名称和描述。你快到了。

$(function() {
  $.fn.atwho.debug = true

  var names1 = [{
      "name": "Jacob",
      "description": "description one description one description one"
    },
    {
      "name": "Isabella",
      "description": "description two description two description two"
    }
  ];

  var names = $.map(names1, function(value, index) { //Here I have only used value
    return {
      'id': index,
      'name': value.name, //Here I take value.name from the object
      'email': value.description //And value.description from the object
    };
  });

  var at_config = {
    at: "@",
    data: names,
    headerTpl: '<div class="atwho-header">Service List <small>↑&nbsp;↓&nbsp;</small></div>',
    insertTpl: '${email}',
    displayTpl: "<li>${name}</li>",
    limit: 200
  }
  $inputor = $('#inputor').atwho(at_config);
  $inputor.caret('pos', 47);
  $inputor.focus().atwho('run');
});