我使用 change(handler) 来监听 textarea 的改变事件,但是只有在 textarea 失去焦点时才会收到事件,而我希望在值改变的同时立即收到事件。
$("#text_object").change(listener);
function listener(dom){
alert("I'm not getting here before the textarea loses focus");
}
我使用 change(handler) 来监听 textarea 的改变事件,但是只有在 textarea 失去焦点时才会收到事件,而我希望在值改变的同时立即收到事件。
$("#text_object").change(listener);
function listener(dom){
alert("I'm not getting here before the textarea loses focus");
}
$('#name').on('change textInput input', function () {
});
然而,我发现同时具有textInput和input事件可能会导致事件触发两次,这是不希望看到的,所以只需执行
$('#name').on('change input', function () { ...
不幸的是,浏览器仅在字段失焦时才能识别更改,因此您可能需要尝试附加一个keyup监听器。不幸的是,这不是最优雅的解决方案。
input
事件,它恰好可以满足你的要求。 - jlh$(document).ready(function(){
$('.addtitle').keyup(function(event) {
if(event.keyCode==13) {
}
});
});
在我的情况下,我会在按下回车键时触发该函数(就像Facebook的函数一样)。
编辑:如果页面上有多个文本区域,您应该这样做:
$(document).ready(function(){
$('textarea[name=mynamevalue]').keyup(function(event) {
if(event.keyCode==13) {
}
});
});
/* Get the current value of the input and save it
* in a data attribute before any change is made to it */
$(document).on('keydown','input', function(){
$(this).data('value',$(this).val());
});
/* Compare the values after the keyup event*/
$(document).on('keyup','input', function(){
if($(this).data('value') != $(this).val()){
console.log($(this).attr('name'));
}
});
setInterval()
,并在失焦事件中清除此间隔,并且我认为这是通过自己捕获输入更改的好方法。var myInterval;
$("#text_object").focus(function (event) {
myInterval = setInterval(function () {
listener(event);
}, 100);
});
$("#text_object").blur(function (event) {
clearInterval(myInterval);
});
function listener(event){
clearInterval(myInterval);
alert("I'm not getting here before the textarea loses focus");
}
$myselector.on('change', function() { /*do something*/ });
$myselector.on('keyup', function() { $(this).blur(); $(this).focus(); });
<script>
$(document).ready(function (d) {
/* set initial value to "" (empty string), and not null
we're going to use this to check if the value of the current text field has been changed */
val = '';
setInterval(function () {
if (val !== $('textarea[name="checktext"]').val()) {
// Value is not the same, fire action
alert('val is different');
// Update the current value
val = $('textarea[name="checktext"]').val();
} else {
// Val is the same as textarea value
}
}, 50);
});
</script>
HTML:
<textarea name="checktext"></textarea>
这个脚本只适用于特定的文本区域,您可以更改它或将val设置为文本输入数组。
我只是向您展示了它背后的思想,使用x毫秒的setInterval来检查文本输入的值是否与val的值或任何您想要使用的变量名相同。如果它们不匹配,则意味着它已被更改,如果它们匹配,则意味着没有更改。
希望您会发现这个有用。
然而,HTML5有解决方案
<script>
$(document).ready(function (d) {
$('textarea[name="checktext"]').on('input', function () {
alert('changed');
});
});
</script>
keydown
或keyup
。 - Andrew Whitaker