在输入框字数限制时可能会遇到监控输入了多少字,如果每次输入事件都执行一次方法会很消耗资源,使用debounce方法监控在一段时间内不管用户输入多少次,只在一定的时间才触发监控事件,这里使用的方法是undescore.js中的
/* debounce监控输入框数据变化 start */
var _debounce = function(func, wait) {
var timeout;
return function() {
var context = this, args = arguments;
var later = function() {
timeout = null;
func.apply(context, args);
};
clearTimeout(timeout);
timeout = setTimeout(later, wait);
};
};
function watchLength(options) { //计算长度
var watchDom = options.watchDom,
targetDom = options.targetDom;
targetDom.text(watchDom.text().length);
var calculateLength = function(){
targetDom.text(watchDom.val().length);
}
watchDom.on('focus input propertyChange',_debounce(calculateLength, 100));
}
/* debounce监控输入框数据变化 end */
// 函数调用
watchLength({
watchDom: $('.intro-inp'),
limitLen: 200,
targetDom: $('.edit-count span'),
});
如果不使用debounce函数包装一下,每次输入框中的值改变需要调用calculateLength进行监控加入debounce则触发事件后每隔对应时间执行一次,这段时间内不管输入多少字符都不计算