비슷한 문제가있어서 내부 응용 프로그램에서 현재 사용중인 jQuery 플러그인을 만들었습니다. 사용자가 입력을 마친 후에는 변경 이벤트가 트리거되어야합니다.
jQuery를 사용하지 않는 경우에도 코드는 다른 어떤 것에도 적용 할 수 있습니다.
jQuery.fn.handleKeyboardChange = function(nDelay)
{
// Utility function to test if a keyboard event should be ignored
function shouldIgnore(event)
{
var mapIgnoredKeys = {
9:true, // Tab
16:true, 17:true, 18:true, // Shift, Alt, Ctrl
37:true, 38:true, 39:true, 40:true, // Arrows
91:true, 92:true, 93:true // Windows keys
};
return mapIgnoredKeys[event.which];
}
// Utility function to fire OUR change event if the value was actually changed
function fireChange($element)
{
if($element.val() != jQuery.data($element[0], "valueLast"))
{
jQuery.data($element[0], "valueLast", $element.val())
$element.trigger("change");
}
}
// The currently running timeout,
// will be accessed with closures
var timeout = 0;
// Utility function to cancel a previously set timeout
function clearPreviousTimeout()
{
if(timeout)
{
clearTimeout(timeout);
}
}
return this
.keydown(function(event)
{
if(shouldIgnore(event)) return;
// User pressed a key, stop the timeout for now
clearPreviousTimeout();
return null;
})
.keyup(function(event)
{
if(shouldIgnore(event)) return;
// Start a timeout to fire our event after some time of inactivity
// Eventually cancel a previously running timeout
clearPreviousTimeout();
var $self = $(this);
timeout = setTimeout(function(){ fireChange($self) }, nDelay);
})
.change(function()
{
// Fire a change
// Use our function instead of just firing the event
// Because we want to check if value really changed since
// our previous event.
// This is for when the browser fires the change event
// though we already fired the event because of the timeout
fireChange($(this));
})
;
}
사용법 :
당신은, 내가 바로 한 한
$("#my_input").handleKeyboardChange(300).change(function()
{
// value has changed!
});
좋은. 당신은 어떤 상황을 고려하지 않았다. –
내가 바꿨다 $ element.trigger ("Keyboard.change"); ~ $ element.trigger ("change"); 순진한 구현이 훨씬 낫습니다. –
아, 죄송합니다. 특정 애플리케이션의 네임 스페이스 이벤트였습니다. 당신은 그것을 바꿀 권리가 있었고 위의 코드를 바꿀 것입니다. –