为什么 jQuery.change() 只在我离开元素时触发? [英] Why does jQuery.change() only trigger when I leave the element?

查看:25
本文介绍了为什么 jQuery.change() 只在我离开元素时触发?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 textarea 元素,我想在输入时打印在 textarea 上方写入的字符数.HTML 如下所示:

I have a textarea element and I want to print the number of characters written, above the textarea, as I'm typing. The HTML looks like this:

<p id="counter"></p>
<textarea id="text"></textarea>

和 javascript:

and the javascript:

jQuery( "#text" ).change( function(){
    var numberOfChars = jQuery( "#text" ).val().length;
    jQuery( "#counter" ).html( numberOfChars );
});

但是当我在文本区域外单击时,计数器只会更新".这是为什么?我希望计数器在我写作时即时更新.

But the counter only "updates" when I click outside the textarea. Why is that? I want the counter to update on the fly as I'm writing.

推荐答案

这是更改事件的已知行为.在元素失去焦点之前它不会触发.来自文档:

this is known behaviour of the change event. It does not fire until the element has lost focus. From the docs:

当元素的值发生变化时,将向元素发送 change 事件.这个事件仅限于元素、框和元素.对于选择框、复选框和单选按钮,事件当用户用鼠标进行选择时立即触发,但对于其他元素类型,事件被推迟到元素失去焦点.

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.

我会将脚本绑定到 keyup(您可以使用其他键事件,但 up 在这种情况下最有意义):

I would bind the script to the keyup instead (you could use the other key events, but up makes the most sense in this context):

jQuery( "#text" ).keyup(function(){
    var numberOfChars = jQuery( "#text" ).val().length;
    jQuery( "#counter" ).html( numberOfChars );
});

这篇关于为什么 jQuery.change() 只在我离开元素时触发?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆