1

我有一堆隐藏的 div,里面有一个表。用户需要在第一个单元格中搜索一个名称(可以包含空格),然后返回 div ID。
我查看了 jQueryUI 自动完成插件,但在使用多个值时遇到了问题。插件文档演示
我使用“自定义数据和显示”示例作为预定义数据数组的基础,但我想避免它并简单地使用选择器。

搜索框

<label for="search_name">Find name</label>
<input type="text" name="search_name" value="" id="search_name">
<span style="display:none;" id="search_result"></span>

分区

<div id="name_101284"><table>
  <tr><th colspan="5">John Doe (<a href="http://link">text</a>) - snip</th></tr>
  <tr><th>C1</th><th>C2</th><th>C3</th><th>C4</th><th>C5</th></tr>
  <tr><td>snip
</table></div>

JS

  var nameAC = [
   {label:"John Doe",id:"101284"},
   {label:"Johnny",id:"152345"},
   {label:"Jim Nelson",id:"77344"},
   {label:"Jimmy",id:"87457"},
   {label:"Maria",id:"100934"},
   {label:"Maria Nelson",id:"94734"},
   {label:"Jane Doe",id:"86247"},
   {label:"Janet",id:"106588"}
  ];
  $('#search_name').autocomplete({
    minLength: 1,
    delay: 300,
    source: nameAC,
    focus: function(event, ui) {
      $('#search_name').val(ui.item.label);
      return false;
    },
    select: function(event, ui) {
      $('#search_result').text(ui.item.id);
      $('#search_result').show();
    }
  });

属性“label”是包含填充下拉结果 UL 的值的预期名称。改变它需要覆盖默认的 _renderItem 方法,像这样

$('#search_name').autocomplete({
 stuff
})
.data("autocomplete")._renderItem = function(ul, item) {
  return $("<li></li>")
  .data("item.autocomplete", item)
  .append("<a>" + item.name + "</a>")
  .appendTo(ul);
};

但它似乎有缺陷。

我可以制作一个选择器(或回调函数)以避免必须制作 nameAC 数组吗?

4

1 回答 1

2

Kim, I think the way you are doing it is pretty solid. If you want to have the source generated by a function, I suggest you make it easier to parse your data, i.e. by putting a span tag around the name in each div.

That being said, here's one way to do it with your data as it is now. It's probably not perfect, thus my suggestion:

function makeArray() {
    var results = [];
    $("div[id^='name_']").each(function() {
        results.push({
            'label': $(this).find('th:first').text().replace(/(.*) \(.*/, '$1'),
            'id': this.id.replace(/name_(\d+)/, '$1')
        });
    });
    return results;
}

Obviously, if your username was something like this: <span class="name">John Doe</span>, then the label would be easier: $(this).find('span.name').text()

You can see a simple version of this in action here: http://jsfiddle.net/ryleyb/MYCbX/

EDIT: I should have mentioned, this is called from the autocomplete like this:

$('#search_name').autocomplete({
    source: makeArray() // <-- note the brackets, function is being **called** 
});
于 2010-11-04T17:11:35.187 回答