0

我正在尝试将片段实现到 html 文本区域中。你写了一个单词,它会查看键值对象并扩展文本(如果存在)。这是我所做的:

var textarea = document.getElementById("whatever");
var snippets = {
    'hello': 'Hello and welcome to my great site'
}
var prepend = "";

var checkCaps = function(e){
  if (e.keyCode != 9) return;
  e.preventDefault();
  var string = "";
  var pos = textarea.selectionStart;
  var text = textarea.value.split("");
  while (pos) {
    char = text.pop(pos);
    prepend =  (char == " ") ? " ": ""; 
    if (char == " ") break;
    string += char 
    pos -= 1;
  }
  if (snippets[string.reverse()]) {
      textarea.value = text.join("")
      textarea.value += prepend + snippets[string.reverse()]
  }
}


textarea.addEventListener("keydown", checkCaps, false);

String.prototype.reverse=function(){return this.split("").reverse().join("");}

http://jsfiddle.net/JjTmd/

问题是该片段仅适用于 textarea 的最后一个单词value,我似乎无法确定问题出在哪里。

4

1 回答 1

1

Array.pop不接受参数。它从数组中删除并返回最后一项。用于splice删除特定索引处的项目。

我按如下方式修改了您的功能,它似乎具有所需的行为:

var checkCaps = function(e){
  if (e.keyCode != 9) return;
  e.preventDefault();
  var string = "";
  var pos = textarea.selectionStart;
  var text = textarea.value.split("");
  while (pos) {
    char = text.splice(pos-1,1);
    prepend =  (char == " ") ? " ": ""; 
    if (char == " ") break;
    string += char 
    pos -= 1;
  }
  if (snippets[string.reverse()]) {
      var start = text.splice(0, pos);
      var end = text.splice(pos + string.length);

      textarea.value = start.join("") + snippets[string.reverse()] + prepend + text.join("") + end.join("");
  }
}

http://jsfiddle.net/JjTmd/1/

此外,您可能还需要检查换行符:

while (pos) {
    char = text.splice(pos-1,1);

      if (char == " " || char == "\n") {
          prepend = char;
          break;
      }
    string += char 
    pos -= 1;
}

http://jsfiddle.net/JjTmd/2/

于 2012-10-02T20:40:30.173 回答