简体   繁体   English

在对象文字函数中访问Jquery对象变量

[英]acessing Jquery object variable inside object literal function

I'm not able to understand why can't I check the .change() method of a jquery object stored in a variable. 我无法理解为什么我不能检查存储在变量中的jquery对象的.change()方法。 Is this a syntax error? 这是语法错误吗? Did I lost the context? 我失去了背景吗?

Here's my code: 这是我的代码:

var MyObj = {

    //declaration
    reference : $('#reference'),
    observeReference : function() {

        //The following line is not tracking the .change() method. 
        //Not sure why... And I didn't any get console error!
        this.reference.change(function() {
            var opt = $('#reference option:selected').text();

            if (opt === 'other' || opt === 'reference') {
                $('#input_other').fadeIn();
            } else{
                $('#input_other').fadeOut();
                $('#input_other_bx').val('');
            };
        }.bind(this));      
    },
    init: function() {
        this.observeReference();
    }
};

$(document).ready(function() {
     MyObj.init();
});

If $('#reference') execute before document ready, it will get a jquery object which length = 0 . 如果$('#reference')在文档就绪之前执行,它将获得一个length = 0的jquery对象。

init method will execute after document ready, so assign reference in init method . init方法将在文件就绪后执行,因此在init方法中分配引用。

var MyObj = {

//declaration
reference : null,
...

init: function() {
    this.reference = $('#reference');
    this.observeReference();
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM