简体   繁体   中英

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. 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 .

init method will execute after document ready, so assign reference in init method .

var MyObj = {

//declaration
reference : null,
...

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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