我有一个 textarea 元素,我想在输入时在 textarea 上方打印所写的字符数。 HTML 看起来像这样:
<p id="counter"></p>
<textarea id="text"></textarea>
和javascript:
jQuery( "#text" ).change( function(){
var numberOfChars = jQuery( "#text" ).val().length;
jQuery( "#counter" ).html( numberOfChars );
});
但当我在文本区域外单击时,计数器只会“更新”。这是为什么?我希望计数器在我写作时即时更新。
最佳答案
这是更改事件的已知行为。在元素失去焦点之前它不会触发。 From the docs:
The change event is sent to an element when its value changes. This event is limited to elements, boxes and elements. For select boxes, checkboxes, and radio buttons, the event is fired immediately when the user makes a selection with the mouse, but for the other element types the event is deferred until the element loses focus.
我会改为将脚本绑定(bind)到 keyup(您可以使用其他按键事件,但在这种情况下 up 最有意义):
jQuery( "#text" ).keyup(function(){
var numberOfChars = jQuery( "#text" ).val().length;
jQuery( "#counter" ).html( numberOfChars );
});
关于javascript - 为什么 jQuery.change() 只在我离开元素时触发?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9567824/