javascript - 访问对象字面量函数内的Jquery对象变量

标签 javascript jquery scope object-literal

我无法理解为什么我不能检查存储在变量中的 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();
}

关于javascript - 访问对象字面量函数内的Jquery对象变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22029032/

相关文章:

javascript - dragenter 在 html5 拖放中的 dragleave 之前调用两次

python - 在 Python 中使 vars 在调用方法范围内可见的方法?

javascript - jQuery id 选择器和 validate.js

javascript - Angular JS 处理 Ng 重复的 HTML5 视频和 $SCE

javascript 密码计不递增

javascript - 如何在不使用隐藏字段的情况下访问 C# 代码中的 javascript 变量

使用 JQuery Boilerplate 的 Javascript 范围问题

javascript - 在调试器中更改局部范围变量

javascript - 在一个页面上同时显示来自 Google 的多个搜索的最佳方式?

javascript - 回调 $interval 函数