2011-03-07 23 views

回答

2

使用keyup函数来触发。拆分所有字符串并检查它。

[更新]:更多的改进版

<script> 

var totalcount=0; 

$(function(){ 

    $('#text').keyup(

     function(){ 

       var arr = $(this).val().split(" "); 

       var matchitems = count('hello', arr); 

       //console.log(matchitems); 

       if(matchitems > totalcount){ 
       alert('hello'); 
       totalcount = matchitems; 
       } 
       if(matchitems < totalcount) 
       { 
       totalcount = matchitems; 
       } 

     } 
    ) 

}) 

function count(value, array) 
{ 
    var j=0; 

    for(var i=0;i<array.length;i++) 
    { 

     if(array[i] == "hello"){ 
      j++;  
     } 
    } 
    return j; 
} 

</script> 

<input type="text" id="text" /> 
}) 

</script> 

<input type="text" id="text" /> 
+0

谢谢,这很好! – Chaddeus 2011-03-07 06:32:50

1

使用keyup像@experimentX提到的是你要去B中的路/ C,则你会知道你的用户已经输入了价值。但是,运行for循环对于每一个键盘事件都是非常昂贵的。相反,因为你知道你想已经是值,您可以使用预设regexp搜索你的价值:

<input type="text" id="text" value="" /> 

<script> 
    $(function() { 
     var $input = $('#text'); 
     $input.keyup(function (e) { 
      var regexp = /\[text\:/i, 
       val = $(this).val(); 
      if (regexp.test(val)) { 
       console.log('i have it: ', val); 
      } 
     }); 
    }); 
</script> 

这里是你如何编写实际regexp一对夫妇的其他方案。

  • 你希望字符串是在输入的开始:var regexp = /^\[text\:/i;
  • 大厦上面的一个,但合并文本前面的空白的任何量你真的想:var regexp = /^\s+?\[text\:/i;
+0

确定你的概念也是令人印象深刻的,但是你有一个错误...(eveytime它将写入console.log中进行单个匹配)。看到我的imrpoved版本。你不能找到没有匹配的东西,并改进你的?然而+1对于reqex概念 – 2011-03-07 06:39:28

+0

是的,我也试过这个代码。如果没有匹配代码,即使在第一场比赛中已经采取了动作之后,它也会匹配每个密码。 – Chaddeus 2011-03-07 23:49:51

+0

虽然,我能够采取该正则表达式并将其用于其他目的。谢谢! – Chaddeus 2011-03-07 23:50:38

相关问题