我写了两个jquery插件,经常导致Chrome崩溃,能帮我分析下么?


我写了两个jquery插件,整合yii framework的ar验证使用,经常导致Chrome崩溃,请大家帮我分析一下原因,谢谢!


 /**
  * Limiter plugin
  */
 ;(function($){

    $.fn.limiter = function(options) {
        var defaults = {
            max: 21,
            tips : null,
            error : null,
            overflow : 'overflow'
        };

        var args = $.extend(defaults, options);

        this.each(function() {
            var me = $(this);
            me.on('keyup', function() {
                var lengthCurrent = $(this).val().length;
                if (args.error != null) {
                    if (lengthCurrent > args.max) {
                        args.error.addClass(args.overflow);
                    } else {
                        args.error.removeClass(args.overflow);
                    }
                }

                var lengthOver = args.max - lengthCurrent;

                if (lengthOver < 0) {
                    lengthOver = 0;
                }

                if (args.tips != null) {
                    args.tips.css('display', 'block').html("您还能输入" + lengthOver + "个字");
                }
            });
        });

        return this;
    };

 })(jQuery);

 /**
  * Numeric plugin
  */

 ;(function($) {

    $.fn.numeric = function(options) {
        var defaults = {
            default: 0,
            allowNegative: true,
        };

        var args = $.extend(defaults, options);

        this.each(function(){
            me = $(this);
            me.on('blur', function() {
                current = $(this);
                var value = $(this).val();
                if (isNaN(value)) {
                    current.val(args.default);
                }
                if (args.allowNegative == false) {
                    if (value < 0) {
                        current.val(args.default);
                    }
                }
            });
        });
        return this;
    };

 })(jQuery);

chrome jquery JavaScript

tomie 9 years, 8 months ago

试了一下代码,有意思,看来以后写插件更好玩,但我也没见 CPU 飙升,所以,应该不是这是这两个插件代码的问题,你看下你说的 yii 的 ar 吧。


 <style>
.tip {
    padding: 10px 20px;
    border: 1px solid gray;
}
.err.overflow {
    border-color: red;
}
.text, .num {
    padding: 10px 20px;
}
</style>



<p class="tip err"> </p>


<input type="text" class="text" />


<hr>


<input type="text" class="num">



<script>
$(document).ready(function() {

    $('.text').limiter({
        max: 21,
        tips : $('.tip'),
        error : $('.err'),
        overflow : 'overflow'
    });

    $('.num').numeric({
        default: 2,
        allowNegative: false
    });
});
</script>

雷蒂亚阿道夫 answered 9 years, 8 months ago

keyup建议加上节流控制

Wei-Z answered 9 years, 8 months ago

导致崩溃的原因一般都是内存泄漏,但是我看了下代码,又没明显的bug,你单独拿出来测试一下,确定是什么原因导致的。

深红的漆黑 answered 9 years, 8 months ago

Your Answer