基于jQuery的监控表单元素变更的小插件
基于jQuery的监控表单元素变化的小插件
对于监控输入框或者下拉框这些表单元素,大家都有很有方法。keyup,keydown,change这些事件去监控都是一种思路,不过基本在都存在缺点。本文采用监控focus和blur事件的方式来实现:focus后开始监控,blur后停止监控,兼容性很好,不多说了,直接上代码了:
实现代码: $.fn.focuschange = function(callback) { return this.each(function() { var state = $.data(this, "focusblurlistener", { validating: true, value: undefined }); var box = $(this); box.unbind(".focusblurlistener").bind("focus.focusblurlistener", function(event) { state.validating = true; state.value = state.value || ""; (function() { if(state.validating) { if(state.value != box.val()) { callback.call(this, event, state.value, box.val()); state.value = box.val(); } setTimeout(arguments.callee, 200); }else{ return; } })(); }).bind("blur.focusblurlistener", function() { state.validating = false; }); }); }; 使用方式: $(function(){ $(selector).focuschange(function(e,oldValue,newValue){ alert('旧值:' + oldValue + ";新值:" + newValue); }); }); 大家也看到源码的实现方式了,focus的时候出发一个不断自我递归的函数监控元素value变化;blur的时候停止监控。