jquery ui autocomplete _renderItem seems to interfere with select event

女生的网名这么多〃 提交于 2019-11-30 03:00:33

问题


My select event doesn't work if I use _renderItem. If I comment out the last block of code where I call _renderItem, the select event works. When I use _renderItem, the select event doesn't fire at all.

var cache = {}, lastXhr; 

$("#hifind-find").autocomplete({
  source: function(request, response) {

    var term = request.term; 
    if (term in cache) {
      response(cache[term]);
      return;
    }

    var posturl = '/hifind/jquery_ui/autocomplete/'+term; 
    lastXhr = $.post(posturl, function(data, status, xhr) {
      cache[term] = data; 
      if (xhr === lastXhr) {
        response(data); 
      } 
    }, 'json');
  },
  delay: 300,
  minLength: 1,
  select: function(event, ui){
    window.location = ui.item.dest;
  }
});

$.ui.autocomplete.prototype._renderItem = function(ul, item) {
  return $("<li></li>")
    .data("item.autocomplete", item)
    .append('<img src="' + iconImgPath + item.flag + '-search.png" class="icon-autocomplete-bundle">' + item.label )
    .appendTo( ul );
};

I get the same result if I do something like...

$("#hifind-find").autocomplete(myConfig).data("autocomplete")._renderItem = renderItemFunction;

Either way, the select doesn't fire. _renderItem does what it's supposed to. It modifies the item and there are no errors, but it seems to break the select.


回答1:


I believe this is because you are not wrapping the item in an anchor (a) tag. Update your code to wrap the img in an anchor and it'll work fine:

$.ui.autocomplete.prototype._renderItem = function(ul, item) {
  return $("<li></li>")
    .data("item.autocomplete", item)
    .append('<a><img src="' + iconImgPath + item.flag + '-search.png" class="icon-autocomplete-bundle">' + item.label + '</a>')
    .appendTo( ul );
};

Here are some examples that might help:

  • Example without including an a tag in the markup generated in _renderItem (select is broken here like in your question): http://jsfiddle.net/MaLqe/

  • Example with an a tag in the generated markup: http://jsfiddle.net/3zSMG/



来源:https://stackoverflow.com/questions/10900401/jquery-ui-autocomplete-renderitem-seems-to-interfere-with-select-event

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!