将自定义标记添加到自动填充

时间:2012-09-12 11:27:42

标签: javascript jquery

我在jQuery中使用自动完成功能如下:

$("#myDiv").autocomplete({
}

这是标准的jQuery自动完成功能:http://jqueryui.com/demos/autocomplete/

生成的li标签是否可以修改为包含额外的标签?

<li class="ui-menu-item" role="menuitem"><a class="ui-corner-all" tabindex="-1">Erlang</a></li>
<a class="ui-corner-all" tabindex="-1">Erlang</a>
<li class="ui-menu-item" role="menuitem"><a class="ui-corner-all" tabindex="-1">Erlang</a></li>

成为(添加测试者):

<li class="ui-menu-item" mytag="tester" role="menuitem"><a class="ui-corner-all" tabindex="-1">Erlang</a></li>
<a class="ui-corner-all" tabindex="-1">Erlang</a>
<li class="ui-menu-item" role="menuitem"><a class="ui-corner-all" tabindex="-1">Erlang</a></li>

2 个答案:

答案 0 :(得分:1)

使用焦点回调功能。像这样......

$(function() {
  var availableTags = [
    "ActionScript",
    "AppleScript",
    "Asp",
    "BASIC",
    "C",
    "C++",
    "Clojure",
    "COBOL",
    "ColdFusion",
    "Erlang",
    "Fortran",
    "Groovy",
    "Haskell",
    "Java",
    "JavaScript",
    "Lisp",
    "Perl",
    "PHP",
    "Python",
    "Ruby",
    "Scala",
    "Scheme"
  ];

  $("#tags").autocomplete({
    source: availableTags,
    focus: function(event, ui) {
        $(".ui-autocomplete li").attr("mytag", "tester");
    }
  });
});​

检查一下 - http://jsfiddle.net/gtND8/

答案 1 :(得分:0)

如果我找对你,那么你可以使用 _renderItem 来做到这一点,例如:

_renderItem: function( ul, item) {        
   return $( "<li></li>" )
      .data( "item.autocomplete", item )
      .append( "<a>"+ item.label + "</a>" )
      .after( "<a>"+ item.label + "</a>" ).addClass("ui-corner-all")
      .attr("tabindex", -1)
  .appendTo( ul );
}

将html显示为:

<li class="ui-corner-all ui-menu-item" tabindex="-1" role="menuitem">
    <a class="ui-corner-all" tabindex="-1">Erlang</a>
</li>
<a class="ui-corner-all" tabindex="-1">Erlang</a>
<li class="ui-corner-all ui-menu-item" tabindex="-1" role="menuitem">
    <a class="ui-corner-all" tabindex="-1"><strong>Erlang</strong></a>
</li>
<a class="ui-corner-all" tabindex="-1"><strong>Erlang</strong></a>

你的意思是这样的......