繁体   English   中英

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

[英]In jQuery, how to detect specified string while user is typing it?

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

使用jQuery,如何为[text:1]连接一个事件监听器。 我想要在用户输入[text: into a text field]时触发事件。

Zurb创建了一个textchange插件,可以提供帮助。 看到他们的“验证文本”示例,我相信它几乎正是你正在寻找的...

http://www.zurb.com/playground/jquery-text-change-custom-event

使用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" />

使用keyup像@experimentX提到的是你想要去的B / C,那么你就知道你的用户已经inputed值,那么方法。 但是,在每个keyup事件中运行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;

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM