简体   繁体   English

在jQuery中使用.keyup计算字符的简单方法

[英]Simple way to count characters using .keyup in jQuery

<input type="text" />

如何在JavaScript / jQuery中编写.keyup input的字符数?

$('input').keyup(function() {
    console.log(this.value.length);
});

keyup is a shortcut method for bind('keyup') . keyupbind('keyup')的快捷方法。
And as of jQuery version 1.7, all of the above are deprecated we are encourage to use the on method to bind events, meaning that the code should look like this: 从jQuery版本1.7开始,以上所有内容都被弃用了,我们鼓励使用on方法绑定事件,这意味着代码应如下所示:

$('input').on('keyup', function() {
    console.log(this.value.length);
});

Example - This will alert out the number of characters 示例 - 这将提示字符数

$('#textBoxId').bind('keyup', function(e){

     alert($(this).val().length);

});

This obviously assumes that the text box has an id of textBoxId. 这显然假设文本框的id为textBoxId。 Otherwise change selector iof don't want to give it an id for some reason 否则更改选择器iof不希望由于某种原因给它一个id

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

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