单击内容可编辑区域时启用自动完成下拉菜单

时间:2018-12-27 19:27:35

标签: javascript jquery jquery-ui autocomplete contenteditable

有一个内容可编辑的span标记,其中包含一些数据。当我编辑span标签内现有的数据时,我需要清除完整数据,然后从自动完成列表中获得建议。我需要的是,当用户单击span标签而不编辑任何现有数据时,我想显示数据。请帮帮我。先感谢您。

1 个答案:

答案 0 :(得分:0)

这是一个基于http://jqueryui.com/autocomplete/#multiple

的非常简单的示例

$(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"
  ];

  function split(val) {
    return val.split(" ");
  }

  function extractLast(term) {
    return split(term).pop();
  }

  function moveCursorToEnd(el) {
    if (typeof el.selectionStart == "number") {
      el.selectionStart = el.selectionEnd = el.value.length;
    } else if (typeof el.createTextRange != "undefined") {
      el.focus();
      var range = el.createTextRange();
      range.collapse(false);
      range.select();
    }
  }

  $("#content")
    // don't navigate away from the field on tab when selecting an item
    .on("keydown", function(event) {
      if (event.keyCode === $.ui.keyCode.TAB &&
        $(this).autocomplete("instance").menu.active) {
        event.preventDefault();
      }
    })
    .autocomplete({
      minLength: 0,
      source: function(request, response) {
        // delegate back to autocomplete, but extract the last term
        response($.ui.autocomplete.filter(
          availableTags, extractLast(request.term)));
      },
      focus: function() {
        // prevent value inserted on focus
        return false;
      },
      select: function(event, ui) {
        var val = $(this).html();
        var terms = split(val);
        // remove the current input
        terms.pop();
        // add the selected item
        terms.push(ui.item.value);
        // add placeholder to get the comma-and-space at the end
        terms.push("");
        $(this).html(terms.join(" "));
        moveCursorToEnd($(this)[0]);
        return false;
      }
    });
});
#content {
  min-width: 1em;
  min-height: 1em;
  border: 1px solid #eee;
  border-radius: 3px;
  padding-left: 1px;
}
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<div class="ui-widget">
  <label for="content">Edit content: </label>
  <span id="content" contenteditable="true">Basic</span>
</div>

如您所见,已对其进行了修改,以使用“”(空格)代替“,”进行拆分和合并。假设您正在创建句子或单词列表,则效果很好。

希望有帮助。