基于jQuery的监控表单元素变化的小插件
http://www.easyui.info/archives/758.html
对于监控输入框或者下拉框这些表单元素,大家都有很有方法。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的时候停止监控。
相关推荐
EdwardSiCong 2020-11-23
85477104 2020-11-17
hhanbj 2020-11-17
81427005 2020-11-11
seoppt 2020-09-13
honeyth 2020-09-13
WRITEFORSHARE 2020-09-13
84483065 2020-09-11
momode 2020-09-11
85477104 2020-08-15
83510998 2020-08-08
82550495 2020-08-03
tthappyer 2020-08-03
84901334 2020-07-28
tthappyer 2020-07-25
TONIYH 2020-07-22
tztzyzyz 2020-07-20
83510998 2020-07-18
81463166 2020-07-17