43

我想在像 StackOverflow 一样按下一个键时获取字符串长度。

显示长度的 StackOverflow 示例

我试图用 来做到这一点onblur,但它不起作用。我该怎么做呢?

4

11 回答 11

46
于 2012-06-15T08:05:48.530 回答
15

UPDATE: Since I wrote this, the input event has gotten a decent level of support. It is still not 100% in IE9, so you will have to wait a bit until IE9 is fully phased out. In light of my answer to this question, however, input is more than a decent replacement for the method I've presented, so I recommend switching.

Use keyup event

var inp = document.getElementById('myinput');
var chars = document.getElementById('chars');
inp.onkeyup = function() {
  chars.innerHTML = inp.value.length;
}
<input id="myinput"><span id="chars">0</span>

EDIT:

Just a note for those that suggest keydown. That won't work. The keydown fires before character is added to the input box or textarea, so the length of the value would be wrong (one step behind). Therefore, the only solution that works is keyup, which fires after the character is added.

于 2012-06-15T08:07:00.637 回答
6

You should bind a function to keyup event

textarea.keyup = function(){
   textarea.value.length....
} 

with jquery

$('textarea').keyup(function(){
   var length = $(this).val().length;
});
于 2012-06-15T08:04:57.687 回答
4

快速而肮脏的方法是简单地绑定到keyup事件。

$('#mytxt').keyup(function(){
    $('#divlen').text('you typed ' + this.value.length + ' characters');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<input type=text id=mytxt >
<div id=divlen></div>

但更好的做法是将可重用函数绑定到多个事件。例如还可以更改(),因此您还可以预期文本更改,例如粘贴(使用上下文菜单,快捷方式也将被 捕获keyup

于 2012-06-15T08:10:32.627 回答
3
 var myString = 'sample String';   var length = myString.length ;

first you need to defined a keypressed handler or some kind of a event trigger to listen , btw , getting the length is really simple like mentioned above

于 2012-06-15T08:07:15.417 回答
3

function cool(d)
{
    alert(d.value.length);
}
<input type="text" value="" onblur="cool(this)">

它将返回字符串的长度

而不是blur使用keydown事件。

于 2012-06-15T08:02:32.353 回答
2

基本上:为元素分配一个keyup处理程序,在其中计算 的长度,如果其长度小于最小值,则将计数写入单独的值。<textarea><textarea><div>

这是一个例子-

var min = 15;
document.querySelector('#tst').onkeyup = function(e){
 document.querySelector('#counter').innerHTML = 
               this.value.length < min 
               ? (min - this.value.length)+' to go...'
               : '';
}
    
body {font: normal 0.8em verdana, arial;}
#counter {color: grey}
<textarea id="tst" cols="60" rows="10"></textarea>
<div id="counter"></div>

于 2012-06-15T08:16:33.867 回答
2

我不确定您尝试过 onblur 是什么意思,但是要获取任何字符串的长度,请使用其 .length 属性,因此对于文本框或文本区域:

document.getElementById("textarea").value.length

当然,将该 ID 更改为实际 ID。

于 2012-06-15T08:03:17.633 回答
2
<html>
<head></head>
<title></title>
<script src="/js/jquery-3.2.1.min.js" type="text/javascript"></script>
<body>
Type here:<input type="text" id="inputbox" value="type here"/>
<br>
Length:<input type="text" id="length"/>
<script type='text/javascript'>
    $(window).keydown(function (e) {
    //use e.which
    var length = 0;
    if($('#inputbox').val().toString().trim().length > 0)
    {
        length = $('#inputbox').val().toString().trim().length;
    }

    $('#length').val(length.toString());
  })
</script>
</body>
</html>
于 2018-09-04T18:03:40.980 回答
1

留下答复(以及问题标题的答案),对于未来的谷歌人......

您可以使用.length来获取字符串的长度。

var x = 'Mozilla'; var 空 = '';

console.log('Mozilla 是 ' + x.length + ' 代码单元长');

/*"Mozilla 有 7 个代码单元" */

console.log('空字符串的长度为' + empty.length);

/*"空字符串的长度为0" */

如果您打算获得发言的长度,textarea 那么 id="txtarea"您可以使用以下代码。

txtarea = document.getElementById('txtarea');
console.log(txtarea.value.length);

您应该能够将其与 BMP Unicode 符号一起使用。如果你想支持像 () 这样的“非 BMP 符号”,那么它是一个边缘情况,你需要找到一些解决方法。

于 2016-07-01T17:31:27.750 回答
0

这就是我编写的用于获取 Unicode 字符中的字符串的函数:

function nbUnicodeLength(string){
    var stringIndex = 0;
    var unicodeIndex = 0;
    var length = string.length;
    var second;
    var first;
    while (stringIndex < length) {

        first = string.charCodeAt(stringIndex);  // returns an integer between 0 and 65535 representing the UTF-16 code unit at the given index.
        if (first >= 0xD800 && first <= 0xDBFF && string.length > stringIndex + 1) {
            second = string.charCodeAt(stringIndex + 1);
            if (second >= 0xDC00 && second <= 0xDFFF) {
                stringIndex += 2;
            } else {
                stringIndex += 1;
            }
        } else {
            stringIndex += 1;
        }

        unicodeIndex += 1;
    }
    return unicodeIndex;
}
于 2020-12-22T10:40:14.607 回答