簡體   English   中英

在對象文字函數中訪問Jquery對象變量

[英]acessing Jquery object variable inside object literal function

我無法理解為什么我不能檢查存儲在變量中的jquery對象的.change()方法。 這是語法錯誤嗎? 我失去了背景嗎?

這是我的代碼:

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();
});

如果$('#reference')在文檔就緒之前執行,它將獲得一個length = 0的jquery對象。

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