jQuery自动完成renderItem和renderItemData之间的区别

时间:2013-09-07 18:46:31

标签: jquery

我试图理解renderItemrenderItemData之间的区别。

我找不到相关的相关文档。

我有以下代码:

$.widget( "custom.catcomplete", $.ui.autocomplete, {
  _renderMenu: function( ul, items ) {
    var that = this,
    currentCategory = "";
    $.each( items, function( index, item ) {
      if ( item.category != currentCategory ) {
        ul.append( "<li class='ui-autocomplete-category'>" + item.category + "</li>" );
        currentCategory = item.category;
      }
      // with following code, when an element is selected
      // in menu list, the corresponding value appears in searchbox
      that._renderItemData( ul, item );
      // with following code, when an element is selected
      // in menu list, the corresponding value does NOT appear in searchbox
      // I override renderItem below
      **// that._renderItem( ul, item );**

    });
  }
});

function  handleSearchBox() {

  var data = [
    { label: "JAMES", category: "PEOPLE" },
  ];

  $( "#search" ).catcomplete({
    delay: 0,
    source: data,
    select: function(event, ui) {
      event.preventDefault();
      str = JSON.stringify(ui)
      // with renderItemData, str = item in source data
      // with renderItem str = {}
      alert(str)
      var selectedObj = ui.item.label
      $("#search").val(selectedObj);
    }
  });
 $("#search").data("custom-catcomplete")._renderItem = function(ul, item) {
                return $("<li></li>").data("item.autocomplete", item)
                    .append("<a>" + item.label + "</a>")
                    .appendTo(ul);
            }; 

}

我的目标是自定义样式菜单li项目。我不知道我哪里出错了。

1 个答案:

答案 0 :(得分:14)

renderItem构建要附加到结果列表的实际列表项(<li>

renderItemData只是一个调用renderItem的包装器方法,并将关联的数据(标签和值)存储到创建的元素中。稍后在从建议框中导航和选择以及选项时使用此数据。

您会发现两者的源代码非常简单:

_renderItemData: function( ul, item ) {
    return this._renderItem( ul, item ).data( "ui-autocomplete-item", item );
},

_renderItem: function( ul, item ) {
    return $( "<li>" )
        .append( $( "<a>" ).text( item.label ) )
        .appendTo( ul );
},

您应该注意_renderMenu实际上是_renderItemData

_renderMenu: function( ul, items ) {
    var that = this;
    $.each( items, function( index, item ) {
        that._renderItemData( ul, item );
    });
},