使用jquery在keyup上返回textarea的匹配文本

时间:2015-01-23 05:21:37

标签: jquery grep textarea

我有一个文本区域,我想监视一个预定的匹配单词或短语列表。我可以如下实现这个,但我遇到的问题是为用户显示匹配的单词和/或短语。例如,如果用户键入“test,test two”,我将如何从grep语句中返回那些匹配的项目以供显示(或通过其他方法)? - 即使div更新为“请避免使用以下单词和/或短语:test1,test two”。

    function isBanned(array, name){
      return $.grep(array, function(i){
        return name.indexOf(i) >= 0;
      }).length > 0;
    }

    var bannedInput = ['test1','test two'];

    $('#eventText').keyup(function(){
      var inputVal = $('#eventText').val();

      var match = isBanned(bannedInput, inputVal.toLowerCase());

      if(match){
        alert("match found"); 
      }
    }); 

2 个答案:

答案 0 :(得分:1)

尝试

var input = $("#eventText"),
    output = $("[for=eventText]"),
    bannedInput = ["test1", "test two"];

input.on("keyup", function (e) {
    var name = e.target.value.toLowerCase()
    , match = $.grep(bannedInput, function (value) {
        return new RegExp(value).test(name)
    });
    if (!!match.length) {
        output.append(
          "<br />Please avoid using the following words and/or phrases: " 
          + "<span class=banned>\"" 
          + match.join(match.length === 1 ? " " : "\"<i>,</i> \"") 
          + "\"</span>")
    } else {
        output.empty()
    }
});

&#13;
&#13;
var input = $("#eventText"),
    output = $("[for=eventText]"),
    bannedInput = ["test1", "test two"];

input.on("keyup", function (e) {
    var name = e.target.value.toLowerCase()
    , match = $.grep(bannedInput, function (value) {
        return new RegExp(value).test(name)
    });
    if (!!match.length) {
        output.append(
          "<br />Please avoid using the following words and/or phrases: " 
          + "<span class=banned>\"" 
          + match.join(match.length === 1 ? " " : "\"<i>,</i> \"") 
          + "\"</span>")
    } else {
        output.empty()
    }
});
&#13;
i {
    color:rgb(0, 0, 0);
}
.banned {
    color:rgb(0, 0, 255);
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input type="text" id="eventText" /><output for="eventText"></output>
&#13;
&#13;
&#13;

答案 1 :(得分:0)

$.map可能会有所帮助:

function isBanned(bannedWords, input){
  return $.map(bannedWords, function(n, i){
    return input.indexOf(n) >= 0 ? n : 0;
  }
}    

isBanned将返回一个数组,该数组的条目是禁止的单词或0.然后您可以使用$.grep获取输入中找到的禁止单词数组:

var filteredWords = isBanned(bannedInput, inputVal.toLowerCase());
var bannedWords = $.grep(filteredWords, function(n, i) {return n !== 0});