文本框字符串长度实时统计jQuery插件,兼容IE6+

效果如图:

/*
 * ====== 字符串长度实时统计插件 =====
 *  author: Jim
 * version: 2.0 | 2013.12.18
 * =================================
*/

;(function($){ $.fn.extend({ // 回调函数在字符串长度统计完成后触发,this指向应用该插件的DOM元素,实参是统计得到的字符串长度; sumOfChars: function (options, callback) { var settings = $.extend({ eType: 'input', // 事件类型 (ps:测试发现'input'事件在IE9下使用退格键删减内容时竟然不能触发!) isByte: true // 统计的长度类型, true表示统计字节(一个汉字两个字节)长度; false表示统计字符长度; }, options || {}); // 当调用该插件时实参仅包含回调函数: typeof arguments[0] === 'function' && (callback = options); this.each(function(){ var self = $(this), type = settings.eType; // 'on'是jQuery 1.7+ 才有的方法 self.on(type, _handler).triggerHandler(type); type === 'input' && self.on('propertychange', function(){ // IE 8- // 如果发生改变的属性不是value就退出 if(!window.event || window.event.propertyName !== 'value') return; // 避免循环调用 $(this).off('propertychange', arguments.callee); _handler.apply(this); $(this).on('propertychange', arguments.callee); }).triggerHandler('propertychange'); }); // 长度统计 function _count (str, b) { return b? str.replace(/[^\x00-\xff]/g, "aa").length : str.length; } // 事件处理程序 function _handler (e) { var num = _count(this.value, settings.isByte); typeof callback === 'function' && callback.apply(this, [num]); } return this; // 返回jQuery对象以使其链式操作得以持续 } }); }(jQuery));

使用示例:

$('#textCont').sumOfChars( function(n){

    // 这里的this指向#textCont
    $('#showleng').text(n);

} );

 

转载于:https://www.cnblogs.com/MyNameIsJim/p/3475871.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值