Detect Once a Certain Word Has Just Been Entered in a Textarea

女生的网名这么多〃 提交于 2019-12-11 06:49:50

问题


Considering features like EditArea's and CodeMirror's autocomplete, I was wondering if, like Dreamweaver, there is a way to detect if the last word you entered is in a certain list then provide the same kind of suggestion box but with the function's arguments. I imagine you would use a regular expression on the entire field or possibly split() the whole thing (or the current line) then use the length attribute of the array to find the last bit of text, then do something involving an indexOf-like operation; however, this seems like it would get a bit resource-intensive. It almost looks like I've answered my own question, but it always helps to fully explain one's quandary, especially publicly. There's gotta be a better solution than mine. I appreciate any input. Thank you.


回答1:


Put the list of words to match in an object, have the text or options to display as the value. Then on keyup or keypress you can get the last word of the text area using a function like:

function showLastWord(id){
  var el = document.getElementById(id);
  var lastWord = el.value.match(/\w+$/);
  return lastWord? lastWord[0] : '';
}

Then check if the word is in the list and do stuff appropriately.

Edit

A small example is:

<textarea onkeyup="showHelp(this);"></textarea>
<script>

var getLastWord = (function() {
    re = /\w+$/;
    return function (s){
      var lastWord = s.match(re);
      return lastWord? lastWord[0] : '';
    }
}());

var keyWords = {foo:'foo was typed',bar:'bar was typed'};

function showHelp(el) {
  var lastWord = getLastWord(el.value);

  // Check for matching own property of keyWords
  if (keyWords.hasOwnProperty(lastWord)) {

    // Do stuff
    console.log(keyWords[lastWord]);
  }
}


来源:https://stackoverflow.com/questions/8206613/detect-once-a-certain-word-has-just-been-entered-in-a-textarea

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