我将以keydown事件监听器为例。
可以使用
$('#my-input').keydown(function(){
//actions goes here
});
我知道上面的事件监听器在遇到keydown事件时会运行。
我需要像这样的“afterkeydown事件”:
$('#my-input').afterkeydown(function(){
//actions after keydown listener has occured
});
但是我不想使用keyup事件监听器或任何类型的计时器来实现这一点 因为当重复保持键并且定时器很慢时,键盘事件侦听器不会触发。
在这些限制下,keydown上的“回调事件监听器”是否可能,如果是这样,是否可以推广到所有Jquery事件监听器?意思是,是否有可能为Jquery创建'afterclick','afterdrop','afterclick',...事件监听器?
答案 0 :(得分:0)
因为听起来你真正想要做的就是在textarea被更改时随时得到通知,这里是我用于该特定问题的一些代码。只要通过键盘,拖放,鼠标等更改内容,它就会调用您的回调...
(function($) {
var isIE = false;
// conditional compilation which tells us if this is IE
/*@cc_on
isIE = true;
@*/
// Events to monitor if 'input' event is not supported
// The boolean value is whether we have to
// re-check after the event with a setTimeout()
var events = [
"keyup", false,
"blur", false,
"focus", false,
"drop", true,
"change", false,
"input", false,
"textInput", false,
"paste", true,
"cut", true,
"copy", true,
"contextmenu", true
];
// Test if the input event is supported
// It's too buggy in IE so we never rely on it in IE
if (!isIE) {
var el = document.createElement("input");
var gotInput = ("oninput" in el);
if (!gotInput) {
el.setAttribute("oninput", 'return;');
gotInput = typeof el["oninput"] == 'function';
}
el = null;
// if 'input' event is supported, then use a smaller
// set of events
if (gotInput) {
events = [
"input", false,
"textInput", false
];
}
}
$.fn.userChange = function(fn, data) {
function checkNotify(e, delay) {
var self = this;
var this$ = $(this);
if (this.value !== this$.data("priorValue")) {
this$.data("priorValue", this.value);
fn.call(this, e, data);
} else if (delay) {
// The actual data change happens aftersome events
// so we queue a check for after
// We need a copy of e for setTimeout() because the real e
// may be overwritten before the setTimeout() fires
var eCopy = $.extend({}, e);
setTimeout(function() {checkNotify.call(self, eCopy, false)}, 1);
}
}
// hook up event handlers for each item in this jQuery object
// and remember initial value
this.each(function() {
var this$ = $(this).data("priorValue", this.value);
for (var i = 0; i < events.length; i+=2) {
(function(i) {
this$.on(events[i], function(e) {
checkNotify.call(this, e, events[i+1]);
});
})(i);
}
});
}
})(jQuery);
用法是:
$("#whatever").userChange(yourCallbackFn, optionalData);