在 jQuery 中,如何在用户输入时检测指定的字符串?

Cha*_*eus 5 javascript jquery jquery-events

就像在 Facebook 上输入评论并点击@用户名一样,它会对此做出反应,让您选择内联的用户名。

使用 jQuery,如何为 [text:1] 连接事件侦听器。[text:我希望当用户输入文本字段时触发一个事件。

San*_*kha 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" />
Run Code Online (Sandbox Code Playgroud)