jQuery UI自动完成 - _renderItem在第一次粘贴

时间:2017-11-07 11:30:57

标签: javascript jquery jquery-ui autocomplete

我正在尝试在粘贴输入时填充自定义渲染的自动完成标签。这是一个小提琴:

https://jsfiddle.net/sq5xyLas/

要进行测试,请将jQuery复制到剪贴板,然后将其粘贴到输入文本框中。什么都没发生。删除该条目并再次粘贴,搜索将触发。为什么.autocomplete("instance")._renderItem不会在第一次粘贴时触发?

var projects = [{
  value: "jquery",
  label: "jQuery",
  desc: "the write less, do more, JavaScript library",
  icon: "jquery_32x32.png"
}, {
  value: "jquery-ui",
  label: "jQuery UI",
  desc: "the official user interface library for jQuery",
  icon: "jqueryui_32x32.png"
}, {
  value: "sizzlejs",
  label: "Sizzle JS",
  desc: "a pure-JavaScript CSS selector engine",
  icon: "sizzlejs_32x32.png"
}];

$(input).autocomplete({
  delay: 200,
  minLength: 3,
  source: projects,
}).autocomplete("instance")._renderItem = function(ul, resultItem) {
  console.log("A paste event has happened")
  return $("<li>")
    .append("<div class='autocomplete-item'><div class='autocomplete-img-container'></div><div> " + resultItem.label + "</div></div>")
      .appendTo(ul);
  };
}
</script>
<textarea id="textarea" class="small-input" placeholder="Add a item"  onkeyup="showResult(this)"></textarea>

更新

将来源更新为

     source: function(request, response) {    
        //Do some AJAX
    }

然而_renderItem仍未解雇。

添加:

  if(dynamicSource){
        response( dynamicSource);
    } 
    else{
        response({});
    }

解决了它。

1 个答案:

答案 0 :(得分:1)

var projects = [{
  value: "jquery",
  label: "jQuery",
  desc: "the write less, do more, JavaScript library",
  icon: "jquery_32x32.png"
}, {
  value: "jquery-ui",
  label: "jQuery UI",
  desc: "the official user interface library for jQuery",
  icon: "jqueryui_32x32.png"
}, {
  value: "sizzlejs",
  label: "Sizzle JS",
  desc: "a pure-JavaScript CSS selector engine",
  icon: "sizzlejs_32x32.png"
}]
$('#textarea').autocomplete({
  minLength: 3,
  source: projects,
}).autocomplete("instance")._renderItem = function(ul, resultItem) {
  console.log("A paste event has happened")
  return $("<li>")
    .append("<div class='autocomplete-item'><div class='autocomplete-img-container'></div><div> " + resultItem.label + "</div></div>")
    .appendTo(ul);
};
<script src="//code.jquery.com/jquery-1.12.4.js"></script>
<script src="//code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<textarea id="textarea" class="small-input" placeholder="Add a item"></textarea>

您无需在密钥发生时始终创建自动填充实例。