为什么jQuery选择器变量不在命名空间内工作?

时间:2013-01-11 19:13:06

标签: javascript jquery variables javascript-namespaces

我很难理解为什么这不起作用。我希望声明多个变量。我做错了什么?

     var message = (function ($) {
        var $modalBody = $('.modal-body'),
            $lblToUser = $modalBody.find('.to-user');
        return {
            toUser: function () {
                $lblToUser.val('To');
                $lblToUser.focus(function () {
                    if (this.value === 'To') this.value = '';
                    $(this).addClass('darker');
                }).blur(function () {
                    if (this.value === '') this.value = 'To';
                    $(this).removeClass('darker');
                });
            },
        };
    })(jQuery);

message.toUser();

2 个答案:

答案 0 :(得分:2)

也许您需要先初始化文档?

$( document ).ready( function () {       // <-------
     var message = (function ($) {
        var $modalBody = $('.modal-body'),
            $lblToUser = $modalBody.find('.to-user');
        return {
            toUser: function () {
                $lblToUser.val('To');
                $lblToUser.focus(function () {
                    if (this.value === 'To') this.value = '';
                    $(this).addClass('darker');
                }).blur(function () {
                    if (this.value === '') this.value = 'To';
                    $(this).removeClass('darker');
                });
            },
        };
    })(jQuery);

    message.toUser();
});

答案 1 :(得分:1)

似乎您在,末尾放错了toUser,可能会导致问题。

 var message = (function ($) {
    var $modalBody = $('.modal-body'),
        $lblToUser = $modalBody.find('.to-user');
    return {
        toUser: function () {
            $lblToUser.val('To');
            $lblToUser.focus(function () {
                if (this.value === 'To') this.value = '';
                $(this).addClass('darker');
            }).blur(function () {
                if (this.value === '') this.value = 'To';
                $(this).removeClass('darker');
            });
        }, // <-----
    };
})(jQuery);

message.toUser();