无法设置未定义的属性'passwordStrength'

时间:2013-12-21 20:44:43

标签: javascript jquery

我有这个代码,并在第一行收到javascript错误:

错误是“无法设置属性'passwordStrength'未定义”

代码:

window.myProject.passwordStrength = function ($, window, document) {
var desc = new Array();
desc[0] = "Very Weak";
desc[1] = "Weak";
desc[2] = "Better";
desc[3] = "Medium";
desc[4] = "Strong";
desc[5] = "Very Strong";
return {
    maxScore: 5,
    allowedScore: 4,
    getStrengthDescription: function(score){
        return desc[score];
    },
    getStrength: function(password){


        var score = 0;

        //if password bigger than 6 give 1 point
        if (password.length > 6) score++;

        //if password has both lower and uppercase characters give 1 point  
        if ((password.match(/[a-z]/)) && (password.match(/[A-Z]/))) score++;

        //if password has at least one number give 1 point
        if (password.match(/\d+/)) score++;

        //if password has at least one special caracther give 1 point
        if (password.match(/.[!,@,#,$,%,^,&,*,?,_,~,-,(,)]/)) score++;

        //if password bigger than 12 give an other 1 point
        if (password.length > 12) score++;
        return score;
    }
};
}(jQuery, window, document);

我在我的页面中将其称为:

<script>
    $(function () {
        $(document).ready(function () {
            var passwordStrength = window.myProject.passwordStrength();
            $('#Password').keyup(function () {
                var strength = passwordStrength.getStrength($(this).val());
}
</script>

2 个答案:

答案 0 :(得分:4)

在为该对象定义新属性之前,必须先定义对象

window.myProject = {};
window.myProject.passwordStrength = function ($, window, document) {

FIDDLE

答案 1 :(得分:1)

我建议你这样做。更简单清洁剂。

jsfiddle: http://jsfiddle.net/VmAHF/

js:

(function ($) {
    var desc = [ 'Very Weak', 'Weak', 'Better', 'Medium', 'Strong', 'Very Strong' ];

    var maxScore = 5,
        allowedScore = 4;

    $.fn.getStrength = function (password) {
        var password = $(this).val(),
            score = 0;

        //if password bigger than 6 give 1 point
        if (password.length > 6) score++;

        //if password has both lower and uppercase characters give 1 point  
        if ((password.match(/[a-z]/)) && (password.match(/[A-Z]/))) score++;

        //if password has at least one number give 1 point
        if (password.match(/\d+/)) score++;

        //if password has at least one special caracther give 1 point
        if (password.match(/.[!,@,#,$,%,^,&,*,?,_,~,-,(,)]/)) score++;

        //if password bigger than 12 give an other 1 point
        if (password.length > 12) score++;
        return score;
    };

    $.fn.getStrengthDescription = function() {
        return desc[$(this).getStrength()];
    };
})(jQuery);

$(document).ready(function () {
    $('#password').keyup(function () {
        $('#strength').text($(this).getStrength());
        $('#strength-description').text($(this).getStrengthDescription());
    });
});