一旦发现某字刚刚被一个textarea进入 [英] Detect Once a Certain Word Has Just Been Entered in a Textarea

查看:98
本文介绍了一旦发现某字刚刚被一个textarea进入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑像EditArea的和codeMIRROR的自动完成功能,我在想,如果,像Dreamweaver,有一种方法来检测,如果你输入的最后一个字是​​在一定的名单,然后提供同类建议箱,但与函数的参数。我想你会用在整场或可能拆分()整个事情(或当前行)一个普通的前pression然后使用数组的长度属性来查找文本的最后一位,然后做一些事情,涉及一个的indexOf样的操作;然而,这似乎像它会变得有点资源密集型。它几乎看起来像我已经回答了我自己的问题,但它总是有助于充分解释自己的困境,尤其是公开。有一定有比我更好的解决方案。我AP preciate任何输入。谢谢你。

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.

推荐答案

把话说在对象匹配的列表中,有文字或选项,以显示作为值。然后在KEYUP或键preSS你可以使用像函数获取文本区的最后一个字:

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.

一个小例子是:

<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]);
  }
}

这篇关于一旦发现某字刚刚被一个textarea进入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆